<?php
namespace newMobile\Controller;

use Think\Controller;

class WechatApiController extends Controller
{
    public function _initialize()
    {
        //parent::_initialize();
        header('Content-Type:application/json;charset=utf-8 ');
        vendor('Weixinpay.WxPayPubHelper');
        vendor('Weixinpay.wechatH5Pay');
        $redis = connectRedis();
        $rdsession = I('post.token');
        $uidString = $rdsession . 'uid';
        $uuid = $redis->get($uidString);
        $store_id = intval($_POST["store_id"]);
        if (empty($store_id)) {
            $storeString = $rdsession . 'storeId';
            $store_id = $redis->get($storeString);
        }
        file_put_contents("session.txt", date("Y-m-d H:i:s") . "wechatAPI_post  " . print_r($_POST, true) . "\r\n", FILE_APPEND);
        $redis = connectRedis();
        $rs1 = $redis->get($rdsession);
        $rs = json_decode($rs1, TRUE);
        $openid = $rs['openid'];
        $loginString = $openid.'login';
        $is_login=$redis->get($loginString);
        if ($is_login) {
            $user_rtopenid = M('users_rtopenid')->where("rtopenid='" . $openid . "'")->find();
            $uid = $user_rtopenid['uid'];
        }
        //file_put_contents("session.txt", date("Y-m-d H:i:s") . "初始化sql1  " . print_r(M('users_rtopenid')->getLastSql(), true) . "\r\n", FILE_APPEND);
        file_put_contents("session.txt", date("Y-m-d H:i:s") . "user_rtopenid1  " . print_r($user_rtopenid, true) . "\r\n", FILE_APPEND);
        file_put_contents("session.txt", date("Y-m-d H:i:s") . "user_rtopenid['uid']1  " . print_r($user_rtopenid['uid'], true) . "\r\n", FILE_APPEND);
        if(empty($uid)){
            $uid=$uuid;
        }
        $member_info=M('member')->where('user_id='.$uid.' and store_id='.$store_id)->find();
        $this->member_id = $member_info['id'];
        file_put_contents("session.txt", date("Y-m-d H:i:s") . "uid  " . print_r($uid, true) . "\r\n", FILE_APPEND);
        $this->uid = $uid;
        $this->store_id = $store_id;
    }

    public function wx_in()
    {
        file_put_contents("session.txt", date("Y-m-d H:i:s") . "wx_in  " .print_r('执行wx_in', true). "\r\n", FILE_APPEND);
        $code = $_POST["code"];
        $store_id = $this->store_id;
        if (empty($code)) {
            $this->ajax_r(0, '参数为空！');
        }
        if (empty($store_id)) {
            $this->ajax_r(3, '店铺信息已失效');
        }
        $store = M('store');
        $store_info = $store->find($store_id);
        if ($store_info['status'] == 0) {
            $this->ajax_r(0, '该店铺已关闭');
        }
        $options   =   D('options');
        $option_name='wx_store_'.$store_id;
        //获取小程序配置
        $w_data['option_name']=$option_name;
        $new_w_data=$options->where($w_data)->find();
        $w_config=json_decode($new_w_data['option_value']);
        $smallRoutineInfo=get_object_vars($w_config);
        $appid = $smallRoutineInfo['APP_KEY'];
        $appsecret =$smallRoutineInfo['APP_SECRET'];
        $url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' . $appid . '&secret=' . $appsecret . '&js_code=' . $code . '&grant_type=authorization_code';
        $rs1 = file_get_contents($url);
        $rs = json_decode($rs1, TRUE);
        //\Think\Log::write("session :\n" . print_r($rs, true) . "\n",'storeApi/session' . date('Y-m-d'));
        if (empty($rs['errcode'])) {
            $rd_session = $this->rd_session(16);
            $rs['rd_session'] = $rd_session;
            $redis = connectRedis();
            $storeString = $rd_session . 'storeId';
            //file_put_contents("session.txt", date("Y-m-d H:i:s") . "storeString  " .print_r($storeString, true). "\r\n", FILE_APPEND);
            $redis->set($storeString, $store_id);
            $rdsession = $rd_session;
            $redis->set($rdsession, json_encode($rs));
            $redis->set('session_key', $rs['session_key']);
            $redis->set('openid', $rs['openid']);
            $redis->set('rd_session', $rd_session);
            //file_put_contents("session.txt", date("Y-m-d H:i:s") . "redis  " .print_r($redis->get($storeString), true). "\r\n", FILE_APPEND);
            //print_r($redis->get($storeString));
            $data['rd_session'] = $rd_session;
            $this->ajax_r(1, '成功', $data);
        } else {
            die($rs1);
        }
    }


    public function auth()
    {
        file_put_contents("session.txt", date("Y-m-d H:i:s") . "auth  " . print_r('执行auth', true) . "\r\n", FILE_APPEND);
        $rd_session = I('post.token');
        $rawData = $_POST['rawData'];
        $signature = I('post.signature');
        if (empty($rd_session) || empty($rawData) || empty($signature)) {
            $this->ajax_r(0, '参数为空！');
        }
        $redis = connectRedis();
        $rdsession = $rd_session;
        $rs1 = $redis->get($rdsession);
        $rs = json_decode($rs1, TRUE);
        $rd_redis = $rs['rd_session'];
        $session_key = $rs['session_key'];
        $openid = $rs['openid'];
        if ($rd_session !== $rd_redis) {
            $this->ajax_r(0, 'session已过期！');
        }
        $str = $rawData . $session_key;
        $signature1 = sha1($str);
        if ($signature != $signature1) {
            $this->ajax_r(0, '签名数据不正确！');
        }
        $loginString = $openid . 'login';
        $is_login = $redis->get($loginString);
        if ($is_login) {  //已登录
            $user_id = $this->uid;
        } else {    //已退出
            if ($this->uid) {  //退出后有tokenuid比如407
                $user_id = $this->uid;
            } else {
                $weixin_info = $rawData;
                $weixin_info = json_decode($weixin_info, true);
                //不存在创建游客账号,不是主动注销
                $user_info = M('users')->where("username='" . $weixin_info['nickName'] . "'")->find();
                if ($user_info) {
                    $youke_id = $user_info['id'];
                } else {
                    $youke['username'] = $weixin_info['nickName'];
                    $youke['password'] = "8888888";
                    $youke['wx_name'] = $weixin_info['nickName'];
                    $youke['ishidden'] = 1;
                    $youke['addtime'] = time();
                    $youke['user_pic'] = $weixin_info['avatarUrl'];
                    $youke['login_time'] = date('Y-m-d H:i:s', time());
                    $youke['sex'] = $weixin_info['gender'];
                    $youke['wx_rtopenid'] = $openid;
                    $youke['type'] = 1;
                    $youke_id = M('users')->add($youke);
                }
                $rtopenid_info['rtopenid'] = $openid;
                $rtopenid_info['uid'] = $youke_id;
                M('users_rtopenid')->add($rtopenid_info);
                file_put_contents("session.txt", date("Y-m-d H:i:s") . "走这里  " . print_r($rtopenid_info, true) . "\r\n", FILE_APPEND);
                $user_id = $youke_id;
                file_put_contents("session.txt", date("Y-m-d H:i:s") . "user_id  " . print_r($user_id, true) . "\r\n", FILE_APPEND);
            }
        }
        $data = array();
        if ($user_id) {
            $uidString = $rd_session . 'uid';
            $redis->set($uidString, $user_id);
            $data['user_id'] = $user_id;
            $this->ajax_r(1, '成功', $data);
        } else {
            $this->ajax_r(0, '失败');
        }
    }

    public function is_bd()
    {
        if ($_POST) {
            $rdsession = I('post.token');
            $redis = connectRedis();
            $rs1 = $redis->get($rdsession);
            $rs = json_decode($rs1, TRUE);
            $openid = $rs['openid'];
            $uid = $this->uid;
            if (empty($uid)) {
                $this->ajax_r(0, '用户信息已失效');
            }
            $userInfo = M('users')->find($uid);
            if (empty($userInfo)) {
                $this->ajax_r(0, '该用户不存在！');
            }
            $user_rtopenid = M('users_rtopenid')->where('rtopenid=' . $openid.' and uid='.$uid)->find();
            if ($user_rtopenid && $userInfo['phone']) {
                $data['is_bd'] = 1;
                $this->ajax_r(1, '你已绑定过该手机号！', $data);
            }else {
                $this->ajax_r(0, '未绑定');
            }
        }
    }

   /* public function bd()
    {
        if ($_POST) {
            $post = I('post.');
            $uid = $this->uid;
            if (empty($uid)) {
                $this->ajax_r(0, '用户信息已失效');
            }
            $rdsession =$post['token'];
            $redis = connectRedis();
            $rs1 = $redis->get($rdsession);
            $rs = json_decode($rs1, TRUE);
            $openid = $rs['openid'];
            $moblie = $post['phone'];
            $sms_captcha = $post['code'];
            if (empty($sms_captcha)) {
                $this->ajax_r(0, '参数为空！');
            }
            $code = $redis->get($moblie);
            $userInfo = M('users')->find($uid);
            if (empty($userInfo)) {
                $this->ajax_r(0, '该用户不存在！');
            }
            if ($code) {
                if ($code == $sms_captcha) {
                    $data['is_bd'] = 1;
                    $mobile_user = M('users')->where("phone='" . $moblie . "'")->find();
                    if ($mobile_user) {
                        $user_rtopenid = M('users_rtopenid')->where("rtopenid='" . $openid. "' and uid=".$mobile_user['id'])->find();
                        if ($user_rtopenid)  {
                            $this->ajax_r(0, '你已绑定过该手机号！', $data);
                        } else {
                            $info['id'] = $mobile_user['id'];
                            if($mobile_user['wx_name']!==$userInfo['wx_name']){
                                $info['wx_name'] = $userInfo['wx_name'];
                                M('users')->save($info);
                            }
                            $rtopenid_info['rtopenid'] = $openid;
                            $rtopenid_info['uid'] = $mobile_user['id'];
                            $rs=M('users_rtopenid')->add($rtopenid_info);
                            if($rs) {
                                M('users')->where('id=' . $uid)->delete();
                                M('users_rtopenid')->where('uid=' . $uid)->delete();
                            }
                        }
                        $now_uid = $mobile_user['id'];
                    } else {
                        $user_rtopenid = M('users_rtopenid')->where("rtopenid='" . $openid. "' and uid=".$uid)->find();
                        $info['id'] = $uid;
                        $info['phone'] = $moblie;
                        $rs = M('users')->save($info);
                        if($rs){
                            if(empty($user_rtopenid)){
                                $rtopenid_info['rtopenid'] = $openid;
                                $rtopenid_info['uid'] = $uid;
                                M('users_rtopenid')->add($rtopenid_info);
                            }
                        }
                        $now_uid = $uid;
                    }
                    if ($rs) {
                        $token = $post['token'];
                        $uidString = $token . 'uid';
                        $redis->set($uidString, $now_uid);
                        $data['uid'] = $now_uid;
                        $data['is_bd'] = 1;
                        $this->ajax_r(1, '绑定成功', $data);
                    }
                } else {
                    $this->ajax_r(0, '短信验证码错误');
                }
            } else {
                $this->ajax_r(0, '短信验证码失效');
            }

        }
    }*/

    public function sendCode()
    {
        $data = I('post.');
        $moblie = $data['phone'];
        $code = rand(1000, 9999);
        $rs = duanxin($code, $moblie);
        if ($rs['resultcode'] == 0) {
            $redis = connectRedis();
            $redis->set($moblie, $code);
            $this->ajax_r(1, '发送成功！');
        } else {
            $data['error'] = $rs['errordescription'];
            $this->ajax_r(0, '发送失败！', $data);
        }
    }

    //首页热销和最新产品
    public function index()
    {
        $store_id = $this->store_id;
        if (empty($store_id)) {
            $this->ajax_r(3, '店铺信息已失效');
        }
        $store = M('store');
        $store_info = $store->find($store_id);
        if ($store_info['status'] == 0) {
            $this->ajax_r(0, '该店铺已关闭');
        }
        $datas = array();
        $lastId = intval(I('post.lastId', 0));
        $Num = trim(I('post.num', 10));
        $shop = M('shop');
        $where = '';
        if ($lastId) {
            $where = ' and ( id<"' . $lastId . '") ';
        }
        $shop_list = $shop->where('ishidden=0 and store_id=' . $store_id . $where)->order('sale_num desc,id desc')->limit(0, $Num)->select();

        if ($shop_list) {
            $this->ajax_r(1, '成功', $shop_list);
        } else {
            $this->ajax_r(0, '该店铺没有商品,请联系管理员');
        }
    }



    //获取店铺信息
    public function getStoreInfo()
    {
        $store_id = $this->store_id;
        $user_id = $this->uid;
        if (empty($store_id)) {
            $this->ajax_r(3, '店铺信息已失效');
        }
        $store = M('store');
        $store_info = $store->find($store_id);
        if ($store_info['status'] == 0) {
            $this->ajax_r(0, '该店铺已关闭');
        }
        $data = array();
        $data['store_info'] = $store_info;
        //店铺详情
        $store_template = M('store_template');
        $store_template_info = $store_template->where('store_id=' . $store_id)->find();
        $data['store_template_info'] = $store_template_info;
        //店铺所在地
        $address['Province'] = getProvinceInfo($store_info['province']);
        $address['City'] = getCityInfo($store_info['city']);
        $address['District'] = getDistrictInfo($store_info['district']);
        $data['address'] = $address;

        $shop = M('shop');
        $count = $shop->where("store_id=$store_id and ishidden=0")->count();
        $data['shop_count'] = $count;
        $coupon_goods = M('coupon_goods');
        $nowtime = date('Y-m-d H:i:s', time());
        $count_coupon =  M('coupon_type')->where("store_id=$store_id  and start_time<='$nowtime' and  end_time>='$nowtime' ")->count();
        file_put_contents("cart.txt", date("Y-m-d H:i:s") . "coupon_goods_sql   " . print_r($coupon_goods->getLastSql(), true) . "\r\n", FILE_APPEND);
        $data['count_coupon'] = $count_coupon;
        //判断收藏
        $users_storecollect = M('users_storecollect');
        if ($user_id) {
            $newstoreinfo['shore_id'] = $store_id;
            $newstoreinfo['user_id'] = $user_id;
            $rsstoreinfo = $users_storecollect->where($newstoreinfo)->select();
            if ($rsstoreinfo) {
                $storecollect_status = 1;
            } else {
                $storecollect_status = 0;
            }
        } else {
            $storecollect_status = 0;
        }
        $data['storecollect_status'] = $storecollect_status;
        if (!empty($data)) {
            $this->ajax_r(1, '成功', $data);
        } else {
            $this->ajax_r(0, '该店铺没有信息,请联系管理员');
        }

    }

    //根据分类获取商品
    public function getShopListByCat()
    {
        $label = intval(I('post.label', 1)); //标签id
        $type = intval(I('post.type', 0)); //分类id
        $store_id = $this->store_id;
        if (empty($store_id)) {
            $this->ajax_r(3, '店铺信息已失效');
        }
        $store = M('store');
        $store_info = $store->find($store_id);
        if ($store_info['status'] == 0) {
            $this->ajax_r(0, '该店铺已关闭');
        }
        $lastId = intval(I('post.lastId'));
        $Num = trim(I('post.num', 10));
        $shop = M('shop');
        $orders = array(
            '1' => 'id desc',
            '2' => 'sale_num desc',
            '3' => 'click_num desc',
            '4' => 'price desc',
            '5' => 'price asc',
        );
        $where = '';
        if (!empty($type)) {
            $where = " and  FIND_IN_SET('$type',store_type_id)";
        }
        if (!empty($lastId)) {
            $shopdetails = $shop->field('yt_shop.id,yt_shop.sale_num,yt_shop.click_num,yt_shop.price')->find($lastId);
            if (empty($shopdetails)) {
                $this->ajax_r(0, '参数错误！');
            }
            if ($label == 1) {
                $where = ' and ( id<"' . $lastId . '") ';
            } elseif ($label == 2) {
                $sale_num = $shopdetails['sale_num'];
                $where = ' and ( sale_num<="' . $sale_num . '") and  id!=' . $lastId;
            } elseif ($label == 3) {
                $click_num = $shopdetails['click_num'];
                $where = ' and ( click_num<="' . $click_num . '") and  id!=' . $lastId;
            } elseif ($label == 4) {
                $price = $shopdetails['price'];
                $where = ' and ( price<="' . $price . '") and  id!=' . $lastId;
            } elseif ($label == 5) {
                $price = $shopdetails['price'];
                $where = ' and ( price>="' . $price . '") and  id!=' . $lastId;
            }
        }
        $shop_list = $shop->field('yt_shop.id,yt_shop.store_id,yt_shop.type_id,yt_shop.store_type_id,yt_shop.crowdfunding_id,yt_shop.title,yt_shop.image,yt_shop.click_num,yt_shop.price,yt_shop.oprice,yt_shop.sale_num,yt_shop.num,yt_shop.tuanselect,yt_shop.is_crowdfunding,yt_shop.dikouquan,yt_shop.envelope_type,yt_shop.redenvelope,yt_shop.envelope_product_id')
            ->where('ishidden=0 and store_id=' . $store_id . $where)
            ->order($orders[$label])
            ->limit(0, $Num)
            ->select();
        //print_r($shop->getLastSql());
        if ($shop_list) {
            $this->ajax_r(1, '成功', $shop_list);
        } else {
            $this->ajax_r(0, '暂无该类商品');
        }
    }


    //获取店铺优惠券
    public function getStoreCoupons()
    {
        //分类
        $user_id = $this->uid;
        $store_id = $this->store_id;
        if (empty($store_id)) {
            $this->ajax_r(3, '店铺信息已失效');
        }
        $store = M('store');
        $store_info = $store->find($store_id);
        $coupon_type = M('coupon_type');
        if ($store_info['status'] == 0) {
            $this->ajax_r(0, '该店铺已关闭');
        }
        $time = date('Y-m-d H:i:s', time());
        $couponsList = $coupon_type->where("store_id=$store_id  and start_time<='$time' and  end_time>='$time' ")->select();

        if (is_array($couponsList)) {
            foreach ($couponsList as $key => $value) {
                if ($user_id) {
                    $rs = get_coupon_user($user_id, $value['coupon_type_id']);
                    if($rs['max_fetch']!==0){
                        if ($rs['num'] >= $rs['max_fetch']) {
                            $couponsList[$key]['coupons_status'] = '2'; //2为已领取
                        }else {
                            $couponsList[$key]['coupons_status'] = '1';//1为未领取
                        }
                    }else {
                        $count=M('coupon')->where('coupon_type_id='.$value['coupon_type_id'])->count();
                        if (($rs['num']+$count) >= $rs['count']) {
                            $couponsList[$key]['coupons_status'] = '2'; //2为已领取
                        }else {
                            $couponsList[$key]['coupons_status'] = '1';//1为未领取
                        }
                    }
                } else {
                    $couponsList[$key]['coupons_status'] = '1';//1为未领取
                }
            }
        }
        $data['data'] = $couponsList;
        if (!empty($couponsList)) {
            $this->ajax_r(1, '成功', $data);
        } else {
            $this->ajax_r(0, '无优惠券');
        }
    }
    public function getShopListbyCoupon()
    {
        $id = I('post.id');
        $lastId = intval(I('post.lastId'));
        $Num = trim(I('post.num', 10));
        if (empty($id)) {
            $this->ajax_r(0, '参数为空');
        }
        $store_id = $this->store_id;
        if (empty($store_id)) {
            $this->ajax_r(3, '店铺信息已失效');
        }
        $store = M('store');
        $store_info = $store->find($store_id);
        if ($store_info['status'] == 0) {
            $this->ajax_r(0, '该店铺已关闭');
        }
        $where='yt_shop.ishidden=0 ';
       if (!empty($lastId)) {
           $shopdetails = M('shop')->field('yt_shop.id,yt_shop.sale_num,yt_shop.click_num,yt_shop.price')->find($lastId);
           if (empty($shopdetails)) {
               $this->ajax_r(0, 'lastId参数错误！');
           }
           $where = ' and ( yt_shop.id<"' . $lastId . '") ';
       }
        $shopList=M('coupon_goods')
            ->field('yt_coupon_goods.*,yt_shop.*')
            ->join('yt_shop ON yt_coupon_goods.goods_id = yt_shop.id','left')
            ->where("yt_coupon_goods.coupon_type_id=$id".$where)
            ->order('yt_shop.id DESC')
            ->limit(0, $Num)
            ->select();
       $count=M('coupon_goods')
           ->field('yt_coupon_goods.*,yt_shop.*')
           ->join('yt_shop ON yt_coupon_goods.goods_id = yt_shop.id','left')
           ->where("yt_coupon_goods.coupon_type_id=$id".$where)
           ->count();
        //print_r(M('coupon_goods')->getLastSql());
        $data['total_num'] = $count;
        $data['data'] = $shopList;
        if (!empty($shopList)) {
            $this->ajax_r(1, '成功', $data);
        } else {
            $this->ajax_r(0, '无优惠券');
        }
    }
    function myCoupons()
    {
        $store_id = $this->store_id;

        $uid = $this->uid;
        if (empty($uid)) {
            $this->ajax_r(0, '用户信息已失效');
        }
        if (empty($store_id)) {
            $this->ajax_r(3, '店铺信息已失效');
        }
        $store = M('store');
        $store_info = $store->find($store_id);
        if ($store_info['status'] == 0) {
            $this->ajax_r(0, '该店铺已关闭');
        }
        $couponModel = M('coupon');
        $lastId = intval(I('post.lastId'));
        $Num = trim(I('post.num', 6));
        $time = date('Y-m-d H:i:s', time());
        $where['yt_coupon.uid'] = $uid;
        $where['yt_coupon.store_id'] = $store_id;
        $where['_string'] = ' yt_coupon.end_time>="'.$time.'"';
        if (!empty($lastId)) {
            $coupondetails = $couponModel->field('yt_daiyan.id')->find($lastId);
            if (empty($coupondetails)) {
                $this->ajax_r(0, '最后ID参数错误！');
            }
            $where['_string'] = ' yt_coupon.coupon_id<' .$lastId;
        }
        $couponsList = $couponModel
            ->field('yt_coupon_type.*,yt_coupon.coupon_code,yt_coupon.coupon_id')
            ->join('yt_coupon_type on yt_coupon_type.coupon_type_id =yt_coupon.coupon_type_id')
            ->where($where)
            ->order('yt_coupon.coupon_id desc')
            ->limit(0,$Num)
            ->select();
        file_put_contents("cart.txt", date("Y-m-d H:i:s") . "sql   " . print_r($couponModel->getLastSql(), true) . "\r\n", FILE_APPEND);
        $data['total_num'] = $couponModel
            ->field('yt_coupon_type.*,yt_coupon.coupon_code,yt_coupon.coupon_id')
                ->join('yt_coupon_type on yt_coupon_type.coupon_type_id =yt_coupon.coupon_type_id')
            ->where($where)
            ->order('yt_coupon.coupon_id desc')->count();
        $data['data'] = $couponsList;
        if (!empty($couponsList)) {
            $this->ajax_r(1, '成功', $data);
        } else {
            $this->ajax_r(0, '暂未领取任何优惠券');
        }
    }

    public function getCoupon()
    {
        $id = I('post.id');
        $uid = $this->uid;
        if (empty($uid)) {
            $this->ajax_r(0, '用户信息已失效');
        }
        if (empty($id)) {
            $this->ajax_r(0, '参数为空');
        }
        if ($uid) {
            $coupon_type = M('coupon_type');
            $coupon = M('coupon');
            $coupon_info = $coupon_type->find($id);
            $count = $coupon->where("coupon_type_id=$id and uid=$uid")->count();
            if ($count >= $coupon_info['max_fetch'] && $coupon_info['max_fetch'] != 0) {
                $code = 0;
                $message = '您已领取超过该优惠券最大领取个数 ！';
            } else {
                $rs = $coupon->where("coupon_type_id=$id and uid=0")->find();
                if ($rs) {
                    $data['coupon_id'] = $rs['coupon_id'];
                    $data['uid'] = $uid;
                    $data['member_id'] = $this->member_id;
                    $data['fetch_time'] = date('Y-m-d H:i:s', time());
                    $data['state'] = 1;
                    $rs = $coupon->save($data);
                    $code = 1;
                    $message = '领取成功！';
                } else {
                    $code = 0;
                    $message = '没有剩余优惠券了！';
                }
            }
        } else {
            $code = 0;
            $message = '您还未登陆！！';
        }
        $this->ajax_r($code, $message);
    }
     public function getDaiyanStatus(){
         $shop_id = I('post.id');
         $uid = $this->uid;
         $store_id =$this->store_id;
         $flag=false;

         if($shop_id){
             $rs=M('order')
                 ->join('yt_order_goods ON yt_order.order_id = yt_order_goods.order_id','left')
                 ->where("yt_order_goods.goods_id=$shop_id and (yt_order.order_state='40' or (yt_order.order_state='20' and yt_order.order_type='2')) and yt_order.refund_state='0' and yt_order.buyer_id=$uid ")
                 ->find();
             if ($rs){
                 $flag=true;
             }else{
                 $shop=M('shop')->find($shop_id);
                 $store_id=$shop['store_id'];
                 $type_id=$shop['type_id'];
                 $shop_id=$shop['id'];
                 //商品代言
                 $rs1=  M('angel')->where("type=1 and type_id=$shop_id and uid=$uid")->find();
                 //店铺代言
                 $rs2=   M('angel')->where("type=2 and type_id=$store_id and uid=$uid")->find();
                 //分类代言
                 $rs3=   M('angel')->where("type=3 and type_id  IN ('".$type_id."') and uid=$uid")->find();
                 if($rs1!=null || $rs2!=null ||$rs3!=null){
                     $flag=true;
                 }
             }
             //判断区域代言
             if($flag==false){
                 $area_angel=M('area_angel');
                 $rs=$area_angel->where('uid='.$uid.' and status=4')->select();
                 $shop=M('shop')->find($shop_id);
                 $store_id=$shop['store_id'];
                 $store_info=M('store')->find($store_id);
                 if($rs){
                     foreach ($rs as $key=>$value){
                         if($value['area_type']==1&&$value['district_id']==$store_info['district']){
                             $flag=true;
                         }
                         if($value['area_type']==2&&$value['city_id']==$store_info['city']){
                             $flag=true;
                         }
                         if($value['area_type']==3&&$value['province_id']==$store_info['province']){
                             $flag=true;
                         }
                     }
                 }
             }
         }elseif($store_id){
             $rs=   M('angel')->where("type=2 and type_id=$store_id and uid=$uid")->find();
             file_put_contents("daiyan.txt", date("Y-m-d H:i:s") . "store_id  " . print_r(M('angel')->getLastSql(), true) . "\r\n", FILE_APPEND);
             file_put_contents("daiyan.txt", date("Y-m-d H:i:s") . "rs   " . print_r($rs, true) . "\r\n", FILE_APPEND);
             if($rs){
                 $flag=true;
             }
         }
         //file_put_contents("daiyan.txt", date("Y-m-d H:i:s") . "flag  " . print_r($flag, true) . "\r\n", FILE_APPEND);
         if (!$flag) {
             $this->ajax_r(0, '该用户无代言该产品资格!');
         } else {
             $this->ajax_r(1, '该用户有代言该产品资格!');
         }
     }
    public function getShopDetails()
    {
        file_put_contents("post.txt", date("Y-m-d H:i:s") . "post   " . print_r($_POST, true) . "\r\n", FILE_APPEND);
        $id = I('post.id');
        $uid = $this->uid;
        $redis = connectRedis();
        $rec_token = I('post.rec_token');
        $uidString = $rec_token . 'uid';
        $rec_id = $redis->get($uidString);
       if (empty($id)) {
            $this->ajax_r(0, '参数为空');
        }
        //足迹
        $shop = M('shop');
        $shop_info = $shop->find($id);
        if (!$shop_info) {
            $this->ajax_r(0, '该产品不存在!');
        }
        if ($shop_info['ishidden'] > 0) {
            $this->ajax_r(0, '该产品已下架!');
        }
        $shopDetails = array();
        if ($shop_info['is_crowdfunding']) {
            $crowdfunding = M('crowdfunding');
            $crowdfunding_info = $crowdfunding->where("goods_id=$id")->find();
            $crowdfunding_info['surplus_time'] = ShengYu_Tian_Shi_Fen(strtotime($crowdfunding_info['end_time']));
            $crowdfunding_info['percent'] = round($crowdfunding_info['now_money'] / $crowdfunding_info['total_money'] * 100, 2);
            $shopDetails['crowdfunding'] = $crowdfunding_info;
        }
        $daiyan_sale_where['uid'] = $uid;
        $daiyan_sale_where['shop_id'] = $id;
        $daiyan_sale = M('daiyan')->where($daiyan_sale_where)->find();
        if ($daiyan_sale) {
            $shopDetails['daiyan_sale'] = $daiyan_sale;
        }
        $shop->where('id=' . $id)->setInc('click_num', 1);
        $shop_info['shop_sku'] = json_decode($shop_info['shop_sku'], true);
        $shopDetails['shop_info'] = $shop_info;
        //拼团
        if ($shop_info['tuanselect'] == 1) {
            $order = M('order');
            $rs_tuan = $order
                ->field('yt_order.order_id,yt_order.buyer_name,yt_order.buyer_mobile,yt_users.user_pic,yt_order.order_id,yt_order.payment_time,yt_order.tuannum,yt_order.buyer_city')
                ->join("yt_order_goods on yt_order_goods.order_id=yt_order.order_id")
                ->join("yt_users on yt_users.id=yt_order.buyer_id")
                ->where("yt_order.tuanselect=1 and yt_order.tuan_is_first_id=0 and yt_order_goods.goods_id=$id and yt_order.order_state='20' and yt_order.refund_state=0")
                ->group('yt_order.order_id')
                ->select();
            foreach ($rs_tuan as $key => $v) {
                $num = get_tuan($v['order_id']);
                $pt_nowtime = time();
                $close_time = $v['payment_time'] + 60 * 60 * 24;
                if ($pt_nowtime < $close_time) {
                    if ($num < $v['tuannum']) {
                        $v['num'] = $v['tuannum'] - $num;
                        $new_rs_tuan[] = $v;
                    }
                }
            }
            $shopDetails['new_rs_tuan'] = $new_rs_tuan;
        }
        //获取相册
        $shop_content = M('shop_content');
        $shop_content_info = $shop_content->where('shop_id=' . $id)->find();
        $shop_content_info['config'] = json_decode($shop_content_info['config'], true);
        $shopDetails['shop_content_info'] = $shop_content_info;
        $image_array = explode(',', $shop_content_info['gallery']);
        $shopDetails['arr_img'] = $image_array;
        $order_goods_evaluate = M('order_goods_evaluate');
        //图片评价
        $img_evaluate_count = $order_goods_evaluate->where("goods_id=$id and  is_show=1 and  image <>''")->count();
        //好评
        $good_evaluate_count = $order_goods_evaluate->where("goods_id=$id and is_show=1 and (scores=5 or scores=4)")->count();
        //差评
        $bad_evaluate_count = $order_goods_evaluate->where("goods_id=$id and  is_show=1 and (scores=1 or scores=2)")->count();
        //中评
        $zhong_evaluate_count = $order_goods_evaluate->where("goods_id=$id and is_show=1 and scores=3")->count();
        $shopDetails['img_evaluate_count'] = $img_evaluate_count;
        $shopDetails['good_evaluate_count'] = $good_evaluate_count;
        $shopDetails['bad_evaluate_count'] = $bad_evaluate_count;
        $shopDetails['zhong_evaluate_count'] = $zhong_evaluate_count;
        //判断收藏
        $users_shopcollect = M('users_shopcollect');
        if ($uid) {
            $newshopinfo['shop_id'] = $id;
            $newshopinfo['user_id'] = $uid;
            $rsshopinfo = $users_shopcollect->where($newshopinfo)->select();
            //print_r($users_shopcollect->getLastSql());
            if ($rsshopinfo) {
                $rsshopinfo_status = 1;
            } else {
                $rsshopinfo_status = 0;
            }
        } else {
            $rsshopinfo_status = 0;
        }
        $shopDetails['rsshopinfo_status'] = $rsshopinfo_status;


        //获取优惠券
        $coupon_goods = M('coupon_goods');
        $coupon_type_id = $coupon_goods->field('coupon_type_id')->where("goods_id=$id")->group('coupon_type_id')->select();
        foreach ($coupon_type_id as $key => $value) {
            if ($key == 0) {
                $coupon_type_ids = $value['coupon_type_id'];
            } else {
                $coupon_type_ids = ',' . $value['coupon_type_id'];
            }
        }
        $coupon_type = M('coupon_type');
        $map['coupon_type_id'] = array('in', $coupon_type_ids);
        $map['range_type'] = 1;
        $map['_logic'] = 'OR';
        $coupons = $coupon_type->where($map)->select();
        $coupons_i = 0;
        foreach ($coupons as $key => $value) {
            $start_time = strtotime($value['start_time']);
            $end_time = strtotime($value['end_time']);
            $nowtime = time();
            if ($start_time <= $nowtime && $end_time >= $nowtime) {
                $new_coupons[$coupons_i] = $value;
                $coupons_i++;
            }
        }
        $shop_count = M('shop')->where('ishidden=0 and store_id=' . $shop_info['store_id'])->count();
        $shop_store_count = M('users_storecollect')->where('shore_id=' . $shop_info['store_id'])->count();
        $shopDetails['uid'] = $uid;
        $shopDetails['shop_count'] = $shop_count;
        $shopDetails['shop_store_count'] = $shop_store_count;
        $shopDetails['coupons'] = $new_coupons;
        if (!empty($shopDetails)) {
            $this->ajax_r(1, '成功!', $shopDetails);
        } else {
            $this->ajax_r(0, '无商品信息!');
        }
    }

    public function getCategory()
    {
        $storeId = $this->store_id;
        $nav_obj = M("store_type");
        $oldid = $storeId;
        $storeId = intval($storeId);
        if (empty($storeId)) {
            $this->ajax_r(3, '店铺信息已失效');
        }
        $store = M('store');
        $store_info = $store->find($storeId);
        if ($store_info['status'] == 0) {
            $this->ajax_r(0, '该店铺已关闭');
        }
        $navs = $nav_obj->where(array('shore_id' => $storeId, 'status' => 1))->order(array("listorder" => "ASC"))->select();
        F("site_store_nav_" . $oldid, $navs);
        import("Think.Tree");
        $tree = new \Tree();
        $tree->init($navs);
        $category = $tree->get_tree_array(0, "");
        if (!empty($category)) {
            $this->ajax_r(1, '成功!', $category);
        } else {
            $this->ajax_r(0, '该店铺暂无添加分类!');
        }
    }

    public function getEvaluate()
    {
        $id = I('post.id');
        if (empty($id)) {
            $this->ajax_r(0, '参数为空!');
        }
        $lastId = intval(I('post.lastId', 0));
        $Num = trim(I('post.num', 10));
        $order_goods_evaluate = M('order_goods_evaluate');
        $where = '';
        if (!empty($lastId)) {
            $where = ' and ( id<"' . $lastId . '") ';
        }
        $count = $order_goods_evaluate->where("goods_id=$id and  is_show=1 " . $where)->order('id desc')->count();
        $evaluates['total_num'] = $count;
        $evaluate = $order_goods_evaluate->where("goods_id=$id and  is_show=1" . $where)->limit(0, $Num)->order('id desc')->select();
        if(is_array($evaluate)){
            foreach ($evaluate as $key=>$value){
                $user_info=M('users')->find($value['uid']);
                $evaluate[$key]['user_image']=$user_info['user_pic'];
                $evaluate[$key]['add']=$user_info['user_pic'];
                $evaluate[$key]['addtime']=date('Y-m-d H:i:s',$user_info['addtime']);
                $evaluate[$key]['again_addtime']=date('Y-m-d H:i:s',$user_info['again_addtime']);
            }
        }
        //图片评价
        $img_evaluate_count = $order_goods_evaluate->where("goods_id=$id and  is_show=1 and  image <>''")->count();
        //好评
        $good_evaluate_count = $order_goods_evaluate->where("goods_id=$id and is_show=1 and (scores=5 or scores=4)")->count();
        //差评
        $bad_evaluate_count = $order_goods_evaluate->where("goods_id=$id and  is_show=1 and (scores=1 or scores=2)")->count();
        //中评
        $zhong_evaluate_count = $order_goods_evaluate->where("goods_id=$id and is_show=1 and scores=3")->count();
        $evaluates['img_evaluate_count'] = $img_evaluate_count;
        $evaluates['good_evaluate_count'] = $good_evaluate_count;
        $evaluates['bad_evaluate_count'] = $bad_evaluate_count;
        $evaluates['zhong_evaluate_count'] = $zhong_evaluate_count;
        $evaluates['evaluate'] = $evaluate;

        if (!empty($evaluates)) {
            $this->ajax_r(1, '成功!', $evaluates);
        } else {
            $this->ajax_r(0, '无评论');
        }
    }

    //收藏 type=1 为商品 2为店铺
    public function collect()
    {
        $user_id = $this->uid;
        $data = I('post.');
        if ($_POST && $user_id) {
            if ($data['type'] == 1 && $data['id']) {
                $newdata['shop_id'] = $data['id'];
                $newdata['user_id'] = $user_id;
                $users_shopcollect = M('users_shopcollect');
                $rs = $users_shopcollect->where($newdata)->select();
                if ($rs) {
                    $this->ajax_r(0, '该商品已收藏！');
                } else {
                    $newdata['addtime'] = time();
                    $rs = $users_shopcollect->add($newdata);
                    $this->ajax_r(1, '收藏成功！');
                }
            }
            if ($data['type'] == 2) {
                $newdata['shore_id'] = $data['id'];
                $newdata['user_id'] = $user_id;
                $users_storecollect = M('users_storecollect');
                $rs = $users_storecollect->where($newdata)->select();
                if ($rs) {
                    $users_storecollect->where($newdata)->delete();
                    $this->ajax_r(2, '取消收藏成功！');
                } else {
                    $newdata['addtime'] = time();
                    $rs = $users_storecollect->add($newdata);
                    $this->ajax_r(1, '收藏成功！');
                }
            }
        } else {
            $this->ajax_r(0, '用户信息已失效！');
        }
    }

    //取消收藏 type=1 为商品 2为店铺
    public function delcollect()
    {
        $user_id = $this->uid;
        if (empty($user_id)) {
            $this->ajax_r(0, '用户信息已失效');
        }
        $data = I('post.');
        if ($_POST && $user_id) {
            if ($data['type'] == 1 && $data['id']) {
                $newdata['shop_id'] = $data['id'];
                $newdata['user_id'] = $user_id;
                $users_shopcollect = M('users_shopcollect');
                $rs = $users_shopcollect->where($newdata)->delete();
                if ($rs) {
                    $this->ajax_r(1, '取消成功！');
                } else {
                    $this->ajax_r(0, '取消失败！');
                }
            }
            if ($data['type'] == 2) {
                $newdata['shore_id'] = $data['id'];
                $newdata['user_id'] = $user_id;
                $users_storecollect = M('users_storecollect');
                $rs = $users_storecollect->where($newdata)->delete();
                print_r($users_storecollect->getLastSql());
                if ($rs) {
                    $this->ajax_r(1, '取消成功！');
                } else {
                    $this->ajax_r(0, '取消失败！');
                }
            }
        }
    }

    public function getCart()
    {
        $uid = $this->uid;
        $storeId = $this->store_id;
        if (empty($uid)) {
            $this->ajax_r(0, '用户信息已失效');
        }
        if (empty($storeId)) {
            $this->ajax_r(3, '店铺信息已失效');
        }
        $store = M('store');
        $store_info = $store->find($storeId);
        if ($store_info['status'] == 0) {
            $this->ajax_r(0, '该店铺已关闭');
        }
        file_put_contents("cart.txt", date("Y-m-d H:i:s") . "uid   " . print_r($uid, true) . "\r\n", FILE_APPEND);
        file_put_contents("cart.txt", date("Y-m-d H:i:s") . "storeId   " . print_r($storeId, true) . "\r\n", FILE_APPEND);
        $lastId = intval(I('post.lastId', 0));
        $Num = trim(I('post.num', 10));
        $shop = M('shop');
        $shop_sku = M('shop_sku');
        $count['num'] = 0;
        $count['price'] = 0;
        $where = '';
        if ($lastId) {
            $where = ' and ( id<"' . $lastId . '") ';
        }
        $cart = M('cart');
        $cart_list = $cart->where('buyer_id=' . $uid . ' and store_id=' . $storeId . $where)->order('cart_id desc')->limit(0, $Num)->select();
        file_put_contents("cart.txt", date("Y-m-d H:i:s") . "sql   " . print_r($cart->getLastSql(), true) . "\r\n", FILE_APPEND);
        $cart_info = array();
        foreach ($cart_list as $key => $v) {
            $shop_id = $v['shop_id'];
            $cart_id = $v['cart_id'];
            $rs_shop = $shop->find($shop_id);
            if (empty($rs_shop)) {
                $cart->where("buyer_id=$uid and cart_id=$cart_id")->delete();
                continue;
            }
            $cart_info[$key]['cart_id'] = $cart_id;
            $cart_info[$key]['shop_picture'] = $rs_shop['image'];
            if ($v['sku_id'] != 0) {
                $rs_shop_sku = $shop_sku->where('sku_id=' . $v['sku_id'])->find();
                $cart_info[$key]['shop_name'] = $rs_shop['title'];
                $cart_info[$key]['sku_spec'] = $rs_shop_sku['sku_spec'];
                $cart_info[$key]['sku_style'] = $rs_shop_sku['sku_style'];
                if ($v['tuanselect'] == 1) {
                    if ($rs_shop_sku['sku_price_tuan']) {
                        $price = $rs_shop_sku['sku_price_tuan'];
                    } else {
                        $price = $rs_shop['tuan_price'];
                    }
                } else {
                    $price = $rs_shop_sku['sku_price'];
                }
            } else {
                $cart_info[$key]['shop_name'] = $rs_shop['title'];
                if ($v['tuanselect'] == '1') {
                    $price = $rs_shop['tuan_price'];
                } else {
                    $price = $rs_shop['price'];
                }
            }
            $invoice = get_web_invoice();
            $start_time = time() - 60 * 60 * 24 * $invoice['web_diyong'];
            $daiyan_info = M('daiyan')->where("uid=$uid and shop_id=$shop_id and time>$start_time")->find();

            if ($daiyan_info) {
                $cart_info[$key]['daiyan_sale'] = $rs_shop['dikouquan'];
            } else {
                $cart_info[$key]['daiyan_sale'] = 0;
            }
            $cart_info[$key]['shop_id'] = $shop_id;
            $cart_info[$key]['sku_id'] = $v['sku_id'];
            $cart_info[$key]['oprice'] = $rs_shop['oprice'];
            $cart_info[$key]['price'] = $price;
            $cart_info[$key]['num'] = $v['num'];
            $count['num'] = $count['num'] + $v['num'];
            $count['price'] = $count['price'] + ($v['num'] * $price);
        }
        $data['total_num'] = $count['num'];
        $data['total_price'] = $count['price'];
        $data['cart_info'] = $cart_info;
        if (!empty($cart_info)) {
            $this->ajax_r(1, '成功', $data);
        } else {
            $this->ajax_r(0, '购物车为空');
        }
    }

    public function getTotalPrice()
    {
        $cartIds = I('post.Ids');
        //print_r($cartIds);
        if (empty($cartIds)) {
            $this->ajax_r(0, '参数为空');
        }
        $cart = M('cart');
        $shop = M('shop');
        $shop_sku = M('shop_sku');
        $total_num = 0;
        $total_price = 0;

        $cartIdArray = explode(",", $cartIds);
        //print_r($cartIdarray);
        $cart_info = array();
        foreach ($cartIdArray as $key => $v) {
            $cartInfo = $cart->where("cart_id=$v")->find();
            $shop_id = $cartInfo['shop_id'];
            $rs_shop = $shop->find($shop_id);
            if (empty($rs_shop)) {
                $cart->where("cart_id=$v")->delete();
                continue;
            }

            if ($cartInfo['sku_id'] != 0) {
                $rs_shop_sku = $shop_sku->where('sku_id=' . $cartInfo['sku_id'])->find();
                $cart_info[$key]['shop_name'] = $rs_shop['title'];
                $cart_info[$key]['sku_spec'] = $rs_shop_sku['sku_spec'];
                $cart_info[$key]['sku_style'] = $rs_shop_sku['sku_style'];
                if ($cartInfo['tuanselect'] == 1) {
                    if ($rs_shop_sku['sku_price_tuan']) {
                        $price = $rs_shop_sku['sku_price_tuan'];
                    } else {
                        $price = $rs_shop['tuan_price'];
                    }
                } else {
                    $price = $rs_shop_sku['sku_price'];
                }
            } else {
                $cart_info[$key]['shop_name'] = $rs_shop['title'];
                if ($cartInfo['tuanselect'] == '1') {
                    $price = $rs_shop['tuan_price'];
                } else {
                    $price = $rs_shop['price'];
                }
            }
            $uid = $cartInfo['buyer_id'];
            $invoice = get_web_invoice();
            $start_time = time() - 60 * 60 * 24 * $invoice['web_diyong'];
            $daiyan_info = M('daiyan')->where("uid=$uid and shop_id=$shop_id and time>$start_time")->find();
            if ($daiyan_info) {
                $daiyan_sale = $rs_shop['dikouquan'];
            } else {
                $daiyan_sale = 0;
            }
            $total_num = $total_num + $cartInfo['num'];
            $total_price = $total_price + ($cartInfo['num'] * $price) - ($cartInfo['num'] * $daiyan_sale);
        }
        $data['total_num'] = $total_num;
        $data['total_price'] = $total_price;
        if (!empty($data)) {
            $this->ajax_r(1, '成功', $data);
        } else {
            $this->ajax_r(0, '购物车为空');
        }
    }


    //添加购物车
    public function add_cart()
    {
        $data = I('post.');
        $uid = $this->uid;
        if (empty($uid)) {
            $this->ajax_r(0, '用户信息已失效');
        }

        $shop_sku = M('shop_sku');
        $shop = M('shop');
        $buygood = I('post.buy_now', 0);
        $shop_id=$data['id'];
        $shop_info = $shop->find($shop_id);
        $num = $data['num'] ? $data['num'] : 1;
        if (empty($data['id']) || empty($uid)) {
            $this->ajax_r(0, '参数为空！');
        }
        //print_r($data['style']);
        if (isset($data['style']) || isset($data['spec'])) {
            //有属性
            $map['shop_id'] = $data['id'];
            if (isset($data['style'])) {
                $map['sku_style'] = $data['style'];
            }
            if (isset($data['spec'])) {
                $map['sku_spec'] = $data['spec'];
            }
            $sku_info = $shop_sku->where($map)->find();
        } else {
            $this->ajax_r(0, '请选择规格或样式！');
        }
        $redis = connectRedis();
        $rec_token = I('post.rec_token');
        file_put_contents("post.txt", date("Y-m-d H:i:s") . "post   " . print_r($_POST, true) . "\r\n", FILE_APPEND);
        $uidString = $rec_token . 'uid';
        $rec_id = $redis->get($uidString);
        file_put_contents("post.txt", date("Y-m-d H:i:s") . "rec_id   " . print_r($rec_id, true) . "\r\n", FILE_APPEND);
        if ($rec_id) {
            $rs = get_daiyan_status($shop_id, $rec_id);
            file_put_contents("post.txt", date("Y-m-d H:i:s") . "代言资格   " . print_r($rs, true) . "\r\n", FILE_APPEND);
            if (!$rs) {
                $this->ajax_r(0, '该用户无代言该产品资格!');
            } else {
                if ($uid) {
                    $daiyan_info['uid'] = $uid;
                    $daiyan_info['bid'] = $rec_id;
                    $daiyan_info['shop_id'] = $shop_id;
                    $daiyan_info['time'] = time();
                    $daiyan_info['member_id'] =$this->member_id;
                    $invoice = get_web_invoice();

                    $start_time = time() - 60 * 60 * 24 * $invoice['web_diyong'];
                    file_put_contents("post.txt", date("Y-m-d H:i:s") . "daiyan_info   " . print_r($daiyan_info, true) . "\r\n", FILE_APPEND);

                    $daiyan = M('daiyan')->where("bid=$rec_id and shop_id=$shop_id and time>$start_time and uid=$uid ")->find();
                    file_put_contents("post.txt", date("Y-m-d H:i:s") . "sql   " . print_r(M('daiyan')->getLastSql(), true) . "\r\n", FILE_APPEND);
                    file_put_contents("post.txt", date("Y-m-d H:i:s") . "daiyan   " . print_r($daiyan, true) . "\r\n", FILE_APPEND);

                    if (!$daiyan) {
                        M('daiyan')->add($daiyan_info);
                        file_put_contents("post.txt", date("Y-m-d H:i:s") . "sql   " . print_r(M('daiyan')->getLastSql(), true) . "\r\n", FILE_APPEND);
                        $buser_info = M('users')->find($uid);
                        if ($buser_info['wx_h5openid'] && $shop_info['dikouquan'] > 0) {
                            $keyword1 = '58代言' . $shop_info['dikouquan'] . '元现金抵扣券';
                            $keyword2 = date('Y-m-d H:i:s', time());
                            send_info_dikouquan($buser_info['wx_h5openid'], $keyword1, $keyword2);
                        }
                    }
                }
            }
        }
        //整理添加数据
        $new_cart['shop_id'] = $data['id'];
        $new_cart['rec_id'] = $rec_id;
        $new_cart['store_id'] = $shop_info['store_id'];
        $new_cart['member_id'] =$this->member_id;
        $new_cart['num'] = $num;
        $new_cart['select'] = 1;
        //$new_cart['recommend_id']=$data['rec_id'];
        $new_cart['tuanselect'] = $data['tuanselect'] ? $data['tuanselect'] : 0;
        $new_cart['ctuan_id'] = $data['ctuan_id'] ? $data['ctuan_id'] : 0;
        if ($sku_info) {
            $new_cart['sku_id'] = $sku_info['sku_id'];
        } else {
            $new_cart['sku_id'] = 0;
        }
        $rs = addcart($uid, $new_cart['shop_id'], $new_cart['sku_id'], $new_cart['num'], $new_cart['tuanselect'], $new_cart['ctuan_id'], $buygood);
        if ($rs == 1) {
            $data['cart_id'] = session('cart_list_id');
            $this->ajax_r(1, '成功加入购物车！', $data);
        } elseif ($rs == 2) {
            $this->ajax_r(0, '不能参加自己所开的团！');
        } elseif ($rs == 3) {
            $this->ajax_r(0, '库存不足！');
        } elseif ($rs == 4) {
            $this->ajax_r(0, '该产品限购！');
        } elseif ($rs == 5) {
            $this->ajax_r(0, '不可重复参团！');
        } elseif ($rs == 6) {
            $this->ajax_r(0, '购买量不得小于起拍量！');
        } else {
            $this->ajax_r(0, '加入购物车失败！');
        }
    }

    function edit_cart()
    {
        if ($_POST) {
            $data = I('post.');
            $uid = $this->uid;
            if (empty($uid)) {
                $this->ajax_r(0, '用户信息已失效');
            }
            $cart_id = $data['id'];
            $num = 0;
            if (empty($cart_id)) {
                $this->ajax_r(0, '参数为空！');

            }
            $sku_style = $data['style'];
            $sku_spec = $data['spec'];
            $cart = M('cart');
            $cart_info = $cart->find($cart_id);
            if (isset($sku_style) || isset($sku_spec)) {
                //有属性
                $map['shop_id'] = $cart_info['shop_id'];
                if (isset($sku_style)) {
                    $map['sku_style'] = $sku_style;
                }
                if (isset($sku_spec)) {
                    $map['sku_spec'] = $sku_spec;
                }
                $sku_info = M('shop_sku')->where($map)->find();
                $field['sku_id'] = $sku_info['sku_id'];
            }
            if ($data['type'] == 1) {
                $num = $cart_info['num'] + 1;
            } elseif ($data['type'] == 2) {
                $num = $cart_info['num'] - 1;
            } else {
                $num = $data['num'];
            }
            if ($num > 0) {
                $shop_info = M('shop')->find($cart_info['shop_id']);
                //检测限购  与起拍量
                if ($shop_info['xz_num'] > 0) {
                    if ($num > $shop_info['xz_num']) {
                        $this->ajax_r(0, '该产品限购！');
                    }
                }
                if ($shop_info['qp_num'] > 0) {
                    if ($num < $shop_info['qp_num']) {
                        $this->ajax_r(0, '购买量不能少于起拍量！');
                    }
                }
                $field['num'] = $num;
                $rs = $cart->where('cart_id=' . $cart_id . ' and buyer_id=' . $uid)->setField($field);
                $cart_info = $cart->find($cart_id);
                $data['sku_spec'] = $cart_info['sku_spec'];
                $data['sku_style'] = $cart_info['sku_style'];
                $data['num'] = $cart_info['num'];
                //print_r($cart->getLastSql());
                if ($rs) {
                    $this->ajax_r(1, '购物车更新成功！', $data);
                } else {
                    $this->ajax_r(0, '购物车更新失败！');
                }
            } else {
                $rs = $cart->where('cart_id=' . $cart_id . ' and buyer_id=' . $uid)->delete();
                if ($rs) {
                    $this->ajax_r(1, '购物车更新成功！');
                } else {
                    $this->ajax_r(0, '更新失败！');
                }
            }
        }
    }

    public function del_cart()
    {
        $uid = $this->uid;
        if (empty($uid)) {
            $this->ajax_r(0, '用户信息已失效');
        }
        $cart_ids = I('post.ids');
        $cart_id = explode(',', $cart_ids);
        $cart = M('cart');
        if (is_array($cart_id)) {
            foreach ($cart_id as $key => $val) {
                $rs = $cart->where('buyer_id=' . $uid . ' and cart_id=' . $val)->delete();
            }
        }
        if ($rs) {
            $this->ajax_r(1, '删除成功');
        } else {
            $this->ajax_r(0, '删除失败');
        }
    }

    //获取订单信息
    public function getOrderDetails()
    {
        $getData = I('post.');
        $uid = $this->uid;
        $store_id = $this->store_id;
        $cart_ids = $getData['cart_ids'];
        if (empty($uid)) {
            $this->ajax_r(0, '用户信息已失效');
        }
        if (empty($store_id)) {
            $this->ajax_r(3, '店铺信息已失效');
        }
        $store = M('store');
        $store_info = $store->find($store_id);
        if ($store_info['status'] == 0) {
            $this->ajax_r(0, '该店铺已关闭');
        }
        if (empty($cart_ids)) {
            $this->ajax_r(0, '参数为空');
        }
        //收货地址
        $address = $this->address($uid);
        //订单商品
        $orderInfo = $this->orderInfo($uid, $store_id, $cart_ids);
        if (empty($orderInfo) || empty($orderInfo['cart_list'])) {
            $this->ajax_r(0, '没有订单信息，请先下单');
        }
        //优惠券
        $coupon = M('coupon');
        $coupon_type = M('coupon_type');
        $rs_coupon = $coupon
            ->field('coupon_type_id,start_time,end_time')
            ->where("uid=$uid and state=1")
            ->group('coupon_type_id')
            ->select();
        $coupons_i = 0;
        $new_coupon_shop_ids = $orderInfo['new_coupon_shop_ids'];
        $rs = M('coupon_goods')->field('coupon_type_id')->where("goods_id in ($new_coupon_shop_ids)")->group('coupon_type_id')->select();
        foreach ($rs as $key => $value) {
            $new_rs[] = $value['coupon_type_id'];
        }
        $new_coupons = $total = array();
        foreach ($rs_coupon as $key => $value) {
            //先判断是否是下单商品可使用的优惠券
            if (in_array($value['coupon_type_id'], $new_rs)) {
                $start_time = strtotime($value['start_time']);
                $end_time = strtotime($value['end_time']);
                $nowtime = time();
                if ($start_time <= $nowtime && $end_time >= $nowtime) {
                    $rs_coupon_type = $coupon_type->find($value['coupon_type_id']);
                    //计算可用优惠券总价格
                    $rs_coupon_goods = M('coupon_goods')->where("coupon_type_id=" . $value['coupon_type_id'])->select();
                    $count_price = 0;
                    $new_coupon_shop_ids = explode(',', $new_coupon_shop_ids);
                    foreach ($rs_coupon_goods as $key => $value) {
                        if (in_array($value['goods_id'], $new_coupon_shop_ids)) {
                            $goods_ids[] = $value['goods_id'];
                        }
                    }
                    foreach ($orderInfo as $key => $value) {
                        foreach ($value as $k => $v) {
                            if (in_array($v['shop_id'], $goods_ids)) {
                                $count_price = $count_price + ($v['price'] * $v['num']);
                            }
                        }
                    }
                    //判断价格
                    if ($rs_coupon_type['at_least'] == 0 || ($rs_coupon_type['at_least'] != 0 && $rs_coupon_type['at_least'] <= $count_price)) {
                        $new_coupons[$coupons_i] = $value;
                        $new_coupons[$coupons_i]['coupon_name'] = $rs_coupon_type['coupon_name'];
                        $new_coupons[$coupons_i]['coupon_type_id'] = $rs_coupon_type['coupon_type_id'];
                        $new_coupons[$coupons_i]['at_least'] = $rs_coupon_type['at_least'];
                        $new_coupons[$coupons_i]['money'] = $rs_coupon_type['money'];
                        if ($rs_coupon_type['at_least'] != 0) {
                            $new_coupons[$coupons_i]['xcy'] = '满' . $rs_coupon_type['at_least'] . '元,减' . $rs_coupon_type['money'] . '元';
                        } else {
                            $new_coupons[$coupons_i]['xcy'] = '无限制,减' . $rs_coupon_type['money'] . '元';
                        }
                        $coupons_i++;
                    }
                }
            }
        }
        $web_qita = get_web_invoice();
        $web_invoice = $web_qita['web_invoice'];
        $web_invoice_array = explode(',', $web_invoice);
        $member_info=M('member')->where('user_id='.$uid.' and store_id='.$store_id)->find();
        $balance=$member_info['money'];
        $data['balance'] = $balance;
        $data['orderInfo'] = $orderInfo;
        $data['address'] = $address;
        $data['coupons'] = $new_coupons;
        $data['web_invoice'] = $web_invoice_array;
        $data['cart_ids'] = $cart_ids;
        if (!empty($data)) {
            $this->ajax_r(1, '成功', $data);
        } else {
            $this->ajax_r(0, '订单信息为空');
        }
    }


    //获取用户地址信息
    public function getAddress()
    {
        $user_id = $this->uid;
        if (empty($user_id)) {
            $this->ajax_r(0, '用户信息已失效');
        }
        $users_address = M('users_address');
        $users_address = $users_address->where('user_id=' . $user_id . ' and is_default=1')->find();
        if (!empty($users_address)) {
            $this->ajax_r(1, '成功', $users_address);
        } else {
            $this->ajax_r(0, '用户地址为空');
        }
    }

    //生成订单 以下字段默认
    //支付单号
    //$data['pay_sn']
    //支付方式名称代码
    //$data['payment_code']
    //支付(付款)时间
    //$data['payment_time']
    //订单完成时间
    //$data['finnshed_time']
    //预存款支付金额
    //$data['pd_amount']
    //评价状态 0未评价，1已评价
    //$data['evaluation_state']
    //订单状态：0(已取消)10(默认):未付款;20:已付款;30:已发货;40:已收货;
    //$data['order_state']
    //退款状态:0是无退款,1是部分退款,2是全部退款
    //$data['refund_state']
    //锁定状态:0是正常,大于0是锁定,默认是0
    //$data['lock_state']
    //退款金额
    //$data['refund_amount']
    //延迟时间,默认为0
    //$data['delay_time']
    //物流单号
    //$data['shipping_code']
    //物流商家
    //$data['shipping_name']
    public function order()
    {
        //统计商品
        $getData = I('post.');
        $uid = $this->uid;
        $store_id = $this->store_id;
        $cart_ids = $getData['cart_ids'];
        if (empty($uid)) {
            $this->ajax_r(0, '用户信息已失效');
        }
        if (empty($store_id)) {
            $this->ajax_r(3, '店铺信息已失效');
        }
        $store = M('store');
        $store_info = $store->find($store_id);
        if ($store_info['status'] == 0) {
            $this->ajax_r(0, '该店铺已关闭');
        }
        if (empty($cart_ids)) {
            $this->ajax_r(0, '参数为空');
        }
        $user_info = M('users')->find($uid);
        /*if ($user_info['phone'] == null) {
            $this->ajax_r(0, '请先去个人中心-关联账户中绑定手机');
        }*/

        //订单商品
        $orderInfo = $this->orderInfo($uid, $store_id, $cart_ids);
        if (empty($orderInfo)) {
            $this->ajax_r(0, '没有订单信息，请先下单');
        }
        //总订单号
        $order_cn = $this->build_order_no();
        $data = array();
        $store = M('store');
        $store_info = $store->find($store_id);
        //获取收货地址
        if($store_info['is_delivery']==1){
            $user_address = get_user_address($uid);
            if ($user_address == null) {
                $this->ajax_r(0, '请添加收货地址');
            }
            //收货地址
            $address = $this->address($uid);
            //买家收货地址ID
            $data['buyer_address_id'] = $user_address['address_id'];
            //收货姓名
            $data['buyer_name'] = $user_address['consigner'];
            //收货省
            $data['buyer_province'] = $user_address['province'];
            //收货市
            $data['buyer_city'] = $user_address['city'];
            //收货区域
            $data['buyer_district'] = $user_address['district'];
            //收货地址
            $data['buyer_address'] = $user_address['address'];
            //收货手机
            $data['buyer_mobile'] = $user_address['mobile'];
            //收货电话
            $data['buyer_phone'] = $user_address['phone'];
            //收货邮编
            $data['buyer_zip_code'] = $user_address['zip_code'];
        }
        //订单总编号
        $data['order_cn'] = $order_cn;
        $order_sn = $this->build_order_no();
        //订单子编号
        $data['order_sn'] = $order_sn;
        //卖家店铺id
        $data['store_id'] = $store_id;
        //卖家店铺名称
        $data['store_name'] = $store_info['title'];
        //买家id
        $data['buyer_id'] = $uid;
        $data['member_id'] =$this->member_id;

        //订单生成时间
        $data['add_time'] = time();
        //1WEB2mobile
        $data['order_from'] = 1;
        //商品总价格
        $data['goods_amount'] = $orderInfo['total_price'];
        //订单总价格
        $data['order_amount'] = $orderInfo['total_price'] + $orderInfo['total_freight'];
        //运费
        $data['shipping_fee'] = $orderInfo['total_freight'];
        $data['invoice_status'] = $getData['invoice_status'] ? $getData['invoice_status'] : 0;
        //发票抬头
        $data['invoice_title'] = $getData['invoice_title'];
        //发票类型
        $data['invoice_content'] = $getData['invoice_content'];
        //留言
        $data['leavemessage'] = $getData['leavemessage'];
        //优惠券种类ID
        $data['coupon'] = $getData['coupon'];
        //是否使用余额
        $data['is_balance'] = $getData['is_balance'];
        $order = M('order');
        $cart = M('cart');
        $order_goods = M('order_goods');
        //开启事物
        $order->startTrans();
        $cart->startTrans();
        $order_goods->startTrans();

        $cart_list = $orderInfo['cart_list'];
        if (empty($cart_list)) {
            $this->ajax_r('0', '订单信息为空，请重新下单');
        }
        $rs_order = $order->add($data);
        if (!$rs_order) {
            $falg = false;
        }
        file_put_contents("order.txt", date("Y-m-d H:i:s") . "rs_order1   " . print_r($rs_order, true) . "\r\n", FILE_APPEND);
        $other_data['daiyan_sale']=0;
        foreach ($cart_list as $key => $value) {
            $shop_info = M('shop')->find($value['shop_id']);
            //免发货设置
            $other_data['mian_send'] = $shop_info['mian_send'];
            $order_good['mian_send'] = $shop_info['mian_send'];
            if ($shop_info['is_crowdfunding'] == '1') {
                $other_data['order_type'] = 2;
            }
            //团购设置
            if ($value['tuanselect'] == 1) {
                $other_data['tuanselect'] = 1;
                $other_data['tuan_is_first_id'] = $value['tuan_id'];
                $tuan_rs = $shop_info;
                $other_data['tuannum'] = $tuan_rs['tuan_num'];
                if ($value['tuan_id']) {
                    $count_num = get_tuan($value['tuan_id']);
                    if ($count_num >= $other_data['tuannum']) {
                        $this->ajax_r(0, $other_data['order_cn'], '该团已满！');
                    }
                }
                $return = M('order')->find($value['tuan_id']);
                if ($return['refund_state'] > 0) {
                    $this->ajax_r(0, $data['order_cn'], '该团已过期！');
                }
            }
            //代言抵扣券 查看
            $shop_id = $value['shop_id'];
            $invoice = get_web_invoice();
            $start_time = time() - 60 * 60 * 24 * $invoice['web_diyong'];
            $daiyan_info = M('daiyan')->where("uid=$uid and shop_id=$shop_id and time>$start_time")->find();

            if ($daiyan_info) {
                $other_data['daiyan_sale'] = $other_data['daiyan_sale']+$shop_info['dikouquan'] * $value['num'];
            } else {
                $other_data['daiyan_sale'] =$other_data['daiyan_sale']+ 0;
            }
            //判断条件
            $falg = true;

            $order_good['order_id'] = $rs_order;
            $order_good['goods_id'] = $value['shop_id'];
            $order_good['goods_name'] = $value['shop_name'];
            $order_good['goods_price'] = $value['price'];
            $order_good['goods_num'] = $value['num'];

            $order_good['goods_image'] = $value['shop_picture'];
            $order_good['goods_pay_price'] = $value['price'] * $value['num'];
            $order_good['goods_sku'] = $value['sku_id'];
            $order_good['goods_sku_spec'] = $value['sku_spec'];
            $order_good['goods_sku_style'] = $value['sku_style'];
            //代言奖励写入
            $order_shop_id = $value['shop_id'];
            /*$order_daiyan_info = M('daiyan')->where("uid=$uid and bid!=$uid and shop_id=$order_shop_id")->find();
            if ($order_daiyan_info && $order_daiyan_info['bid'] != $order_daiyan_info['uid']) {
                $recommend_id = $order_daiyan_info['bid'];
            } else {
                $recommend_id = 0;
            }*/
            file_put_contents("post.txt", date("Y-m-d H:i:s") . "recommend_id   " . print_r($value['rec_id'], true) . "\r\n", FILE_APPEND);
            $order_good['recommend_id'] = $value['rec_id'];
            if ($value['rec_id'] > 0) {
                $order_shop_info = M('shop')->find($value['shop_id']);
                $order_good['recommend_type'] = $order_shop_info['envelope_type'];
                //红包奖励
                if ($order_shop_info['envelope_type'] == 0) {
                    $order_good['recommend_price'] = $order_shop_info['redenvelope'] * $value['num'];
                    $order_good['recommend_shop_id'] = 0;
                    $order_good['recommend_shop_num'] = 0;
                }
                //礼品奖励
                if ($order_shop_info['envelope_type'] == 1) {
                    $order_good['recommend_price'] = 0;
                    $order_good['recommend_shop_id'] = $order_shop_info['envelope_product_id'];
                    if ($order_shop_info['envelope_product_type'] == 0) {
                        $order_good['recommend_shop_num'] = 1;
                    }
                    if ($order_shop_info['envelope_product_type'] == 1) {
                        $order_good['recommend_shop_num'] = $value['num'];
                    }
                }
            }
            $order_good['store_id'] = $value['store_id'];
            $order_good['buyer_id'] = $uid;
            $order_good['member_id'] =$this->member_id;
            $order_good['goods_type'] = 1;
            $order_good['freight'] = $value['freight'];
            $rs_good = $order_goods->add($order_good);
            if (!$rs_good) {
                $falg = false;
            }
            $rs_cart = $cart->delete($value['cart_id']);
            if (!$rs_cart) {
                $falg = false;
            }
        }
        $other_data['order_id']=$rs_order;
        $rs_order2 = $order->save($other_data);
        if (!$rs_order2) {
            $falg = false;
        }
        if ($falg) {
            $order->commit();
            $cart->commit();
            $order_goods->commit();
            //添加订单信息到redis监控
            addredis($data['order_cn']);
            $this->ajax_r(1, '下单成功', $data['order_cn']);
        } else {
            $order->rollback();
            $cart->rollback();
            $order_goods->rollback();
            $this->ajax_r(0, '失败');
        }

    }

    //支付信息
    public function orderQuery()
    {
        $order_cn = I('post.order_no');
        if (empty($order_cn)) {
            $this->ajax_r(0, '参数为空');
        }
        $total_price = 0;
        $status = get_order_status($order_cn, '10');
        if ($status) {
            $order = M('order');
            $result = $order->where('order_cn=' . $order_cn)->select();
            $member_info=M('member')->find($this->member_id);
            $total_balance=$member_info['money'];
            //file_put_contents("order.txt", date("Y-m-d H:i:s") . "总total_balance   " . print_r($total_balance, true) . "\r\n", FILE_APPEND);
            if ($result) {
                foreach ($result as $key => $value) {
                    $order_status = $this->orderQuery2($value['order_cn'], $value['store_id']);
                    $order_status2 = $this->orderQuery2($value['order_sn'], $value['store_id']);
                    if ($order_status || $order_status2) {
                        $this->ajax_r(2, '该订单已支付成功！');
                    }
                    $time = $value['add_time'];
                    if ($value['coupon'] != null) {
                        $youhui_price = get_coupon_price($value['buyer_id'], $value['coupon']);
                    }
                    $total_price = $total_price + $value['order_amount'] - $value['daiyan_sale'] - $youhui_price;
                    if($value['is_balance']==1){
                         if($total_balance>$total_price){ //余额大于支付金额
                             $balance_use=$total_price;
                             $total_balance=$total_balance-$total_price;
                             $total_price=0;
                         }else{//余额小于或等于支付金额
                             $balance_use=$total_balance;
                             $total_price=$total_price-$total_balance;
                             $total_balance=0;
                         }
                         $order_data['order_id']=$value['order_id'];
                         $order_data['balance_use']=$balance_use;
                         $order->save($order_data);
                    }
                    //file_put_contents("order.txt", date("Y-m-d H:i:s") . "$key-total_balance   " . print_r($total_balance, true) . "\r\n", FILE_APPEND);
                }
                //file_put_contents("order.txt", date("Y-m-d H:i:s") . "最后total_balance   " . print_r($total_balance, true) . "\r\n", FILE_APPEND);
            } else {
                $result = $order->where('order_sn=' . $order_cn)->find();
                $order_status = $this->orderQuery2($result['order_cn'], $result['store_id']);
                $order_status2 = $this->orderQuery2($result['order_sn'], $result['store_id']);
                if ($order_status || $order_status2) {
                    $this->ajax_r(2, '该订单已支付成功！');
                }
                $youhui_price = get_coupon_price($result['buyer_id'], $result['coupon']);
                $total_price = $result['order_amount'] - $result['daiyan_sale'] - $youhui_price;
                if($result['is_balance']==1){
                    if($total_balance>$total_price){ //余额大于支付金额
                        $balance_use=$total_price;
                        $total_balance=$total_balance-$total_price;
                        $total_price=0;
                    }else{//余额小于或等于支付金额
                        $balance_use=$total_balance;
                        $total_price=$total_price-$total_balance;
                        $total_balance=0;
                    }
                    $order_data['order_id']=$result['order_id'];
                    $order_data['balance_use']=$balance_use;
                    $order->save($order_data);
                }
                //file_put_contents("order.txt", date("Y-m-d H:i:s") . "最后total_balance   " . print_r($total_balance, true) . "\r\n", FILE_APPEND);
            }
            $data['order_no'] = $order_cn;
            $data['total_price'] = $total_price;
           // file_put_contents("order.txt", date("Y-m-d H:i:s") . "total_price   " . print_r($total_price, true) . "\r\n", FILE_APPEND);
            if ($total_price <= 0) {
                update_order_status($_POST['order_no'], $_POST['order_no'], '20', '无需支付');
                //用户余额扣除
                $memberInfo=M('member')->find($this->member_id);
                $member_data['id']=$this->member_id;
               // file_put_contents("order.txt", date("Y-m-d H:i:s") . "memberInfo['money']   " . print_r($memberInfo['money'], true) . "\r\n", FILE_APPEND);
                $member_data['money']=$total_balance;
                //file_put_contents("order.txt", date("Y-m-d H:i:s") . "member_data['money']  " . print_r($member_data['money'], true) . "\r\n", FILE_APPEND);

                M('member')->save($member_data);
                $this->ajax_r(2, '无需支付！');
            } else {
                $this->ajax_r(1, '成功！', $data);
            }
        } else {
            $this->ajax_r(0, '订单状态不正确，请检查！');
        }
    }

    //微信使用jsapi接口start
    function wechatpay()
    {
        $code = I('post.code');
        $token = I('post.token');
        $order_cn = I('post.order_no');
        $store_id = $this->store_id;
        if (empty($store_id)) {
            $this->ajax_r(3, '店铺信息已失效');
        }
        $store = M('store');
        $store_info = $store->find($store_id);
        if ($store_info['status'] == 0) {
            $this->ajax_r(0, '该店铺已关闭');
        }
        $status = get_order_status($order_cn, '10');
        if ($status) {
            $order = M('order');
            $result = $order->where('order_cn='.$order_cn)->select();
            $count_price = 0;
            if ($result) {
                foreach ($result as $key => $value) {
                    //$goods=$order_goods->field('yt_order_goods.goods_name')->where('order_id='.$value['order_id'])->find();
                    if ($value['coupon'] != null) {
                        $youhui_price = get_coupon_price($value['buyer_id'], $value['coupon']);
                    }
                    $count_price = $count_price + $value['order_amount'] - $value['daiyan_sale'] - $youhui_price-$value['balance_use'];
                }
            } else {
                $result = $order->where('order_sn=' . $order_cn)->find();
                $youhui_price = get_coupon_price($result['buyer_id'], $result['coupon']);
                $count_price = $result['order_amount'] - $result['daiyan_sale'] - $youhui_price-$result['balance_use'];
            }
            $store = M('store');
            $store_info = $store->find($store_id);
            $store_name = $store_info['title'];
            //=========步骤1：网页授权获取用户openid============
            $openIdResult = $this->getOpenId($code, $store_id);
            if (empty($openIdResult['errcode'])) {
                $openid = $openIdResult['openid'];
            } else {
                die(json_encode($openIdResult));
            }
            //file_put_contents("pay.txt", date("Y-m-d H:i:s") . "total_fee   " .print_r($count_price*100, true). "\r\n", FILE_APPEND);
            //=========步骤2：使用统一支付接口，获取prepay_id============
            //使用统一支付接口
            $unifiedOrder = new \UnifiedOrder_pub();
            /*此处做数据库的查询  这里操作数据库把产品信息显示出来*/

            //设置统一支付接口参数
            //设置必填参数
            //appid已填,商户无需重复填写
            //mch_id已填,商户无需重复填写
            //noncestr已填,商户无需重复填写
            //spbill_create_ip已填,商户无需重复填写
            //sign已填,商户无需重复填写
            //

            //设置统一支付接口参数
            //设置必填参数
            $options   =   D('options');
            $option_name='wx_store_'.$store_id;
            //获取小程序配置
            $w_data['option_name']=$option_name;
            $new_w_data=$options->where($w_data)->find();
            $w_config=json_decode($new_w_data['option_value']);
            $smallRoutineInfo=get_object_vars($w_config);
            $appid = $smallRoutineInfo['APP_KEY'];
            $mch_id =$smallRoutineInfo['MCHID'];
            $key = $smallRoutineInfo['MCHID_KEY'];
            file_put_contents("app.txt", date("Y-m-d H:i:s") . "wechatpay接口  " . "\r\n", FILE_APPEND);
            file_put_contents("app.txt", date("Y-m-d H:i:s") . "appid  " . print_r($appid, true) . "\r\n", FILE_APPEND);
            file_put_contents("app.txt", date("Y-m-d H:i:s") . "mch_id  " . print_r($mch_id, true) . "\r\n", FILE_APPEND);
            file_put_contents("app.txt", date("Y-m-d H:i:s") . "key  " . print_r($key, true) . "\r\n", FILE_APPEND);

            $unifiedOrder->setAPPID($appid);
            $unifiedOrder->setMCHID($mch_id);
            $unifiedOrder->setMCHKEY($key);
            $unifiedOrder->setParameter("appid", $appid);//APPID
            $unifiedOrder->setParameter("mch_id", $mch_id);//商户号$openid
            //$unifiedOrder->setParameter("key",$key);//APPID
            //$unifiedOrder->setParameter("openid",$openid);//openid
            $unifiedOrder->setParameter("openid", $openid);//openid
            $unifiedOrder->setParameter("body", $store_name);//商品描述
            //自定义订单号，此处仅作举例
            $unifiedOrder->setParameter("out_trade_no", $order_cn);//商户订单号
            $unifiedOrder->setParameter("total_fee", $count_price * 100);//总金额
            $unifiedOrder->setParameter("notify_url", 'https://m.58daiyan.com/WechatApi/wxnotify');//通知地址
            $unifiedOrder->setParameter("trade_type", "JSAPI");//交易类型
            //非必填参数，商户可根据实际情况选填
            //$unifiedOrder->setParameter("sub_mch_id","XXXX");//子商户号
            //$unifiedOrder->setParameter("device_info","XXXX");//设备号
            $unifiedOrder->setParameter("attach", $token);//附加数据
            //$unifiedOrder->setParameter("time_start","XXXX");//交易起始时间
            //$unifiedOrder->setParameter("time_expire","XXXX");//交易结束时间
            //$unifiedOrder->setParameter("goods_tag","XXXX");//商品标记
            //$unifiedOrder->setParameter("openid","XXXX");//用户标识
            //$unifiedOrder->setParameter("product_id","XXXX");//商品ID


            // print_r($unifiedOrderResult);
            //从统一支付接口获取到code_url(二维码)

            //商户自行增加处理流程
            //......
            //file_put_contents("sign.txt", date("Y-m-d H:i:s") . "unifiedOrder接口   " .print_r('unifiedOrder接口', true). "\r\n", FILE_APPEND);


            $prepay_id = $unifiedOrder->getPrepayId();
            //$prepay_id = $unifiedOrder->getRoutinePrepayId($appid,$mch_id,$key);
            if ($prepay_id['return_code'] == 'FAIL') {
                $this->ajax_r(0, $prepay_id['return_msg']);
            }
            //$prepay_id=$prepay_id['prepay_id'];
            // print_r($prepay_id);

            // echo $prepay_id;exit();
            //=========步骤3：使用jsapi调起支付============
            // file_put_contents("sign.txt", date("Y-m-d H:i:s") . "JsApi_pub接口   " .print_r('JsApi_pub接口', true). "\r\n", FILE_APPEND);

            $jsApi = new \JsApi_pub();
            $jsApi->setAPPID($appid);
            $jsApi->setMCHID($mch_id);
            $jsApi->setMCHKEY($key);
            $jsApi->setPrepayId($prepay_id);

            $jsApiParameters = $jsApi->getParameters();
            // file_put_contents("sign.txt", date("Y-m-d H:i:s") . "jsApiObj   " .print_r($jsApiParameters, true). "\r\n", FILE_APPEND);

            //print_r($jsApiParameters);
            $data = (array)json_decode($jsApiParameters);
            // file_put_contents("sign.txt", date("Y-m-d H:i:s") . "data   " .print_r($data, true). "\r\n", FILE_APPEND);

            unset($data['appId']);
            $this->ajax_r(1, '成功！', $data);
        } else {
            $this->ajax_r(0, '订单状态不正确，请检查！');
        }

    }

    public function wxnotify()
    {
        //使用通用通知接口
        $notify = new \Notify_pub();
        //存储微信的回调
        // $xml = $GLOBALS['HTTP_RAW_POST_DATA'];
        $xml = file_get_contents('php://input');
        //file_put_contents("wxnotify.txt", date("Y-m-d H:i:s") . "xml:   " .print_r($xml, true). "\r\n", FILE_APPEND);
        $redis = connectRedis();
        $parameter = $notify->xmlToArray($xml);
        //file_put_contents("wxnotify.txt", date("Y-m-d H:i:s") . "parameter:   " .print_r($parameter, true). "\r\n", FILE_APPEND);

        $token = $parameter['attach'];
        //file_put_contents("wxnotify.txt", date("Y-m-d H:i:s") . "token:   " .print_r($token, true). "\r\n", FILE_APPEND);
        $storeString = $token . 'storeId';
        $store_id = $redis->get($storeString);
        //file_put_contents("pay.txt", date("Y-m-d H:i:s") . "store_id:   " .print_r($store_id, true). "\r\n", FILE_APPEND);
        $options   =   D('options');
        $option_name='wx_store_'.$store_id;
        //获取小程序配置
        $w_data['option_name']=$option_name;
        $new_w_data=$options->where($w_data)->find();
        $w_config=json_decode($new_w_data['option_value']);
        $smallRoutineInfo=get_object_vars($w_config);
        $appid = $smallRoutineInfo['APP_KEY'];
        $mch_id =$smallRoutineInfo['MCHID'];
        $key = $smallRoutineInfo['MCHID_KEY'];
        $notify->setAPPID($appid);
        $notify->setMCHID($mch_id);
        $notify->setMCHKEY($key);
        $notify->saveData($xml);
        // var_dump($xml);
        //验证签名，并回应微信。
        //对后台通知交互时，如果微信收到商户的应答不是成功或超时，微信认为通知失败，
        //微信会通过一定的策略（如30分钟共8次）定期重新发起通知，
        //尽可能提高通知的成功率，但微信不保证通知最终能成功。
        if ($notify->checkSign() == FALSE) {
            $notify->setReturnParameter("return_code", "FAIL");//返回状态码
            $notify->setReturnParameter("return_msg", "签名失败");//返回信息
        } else {
            $notify->setReturnParameter("return_code", "SUCCESS");//设置返回码
        }
        $returnXml = $notify->returnXml();

        $out_trade_no = $parameter['out_trade_no'];
        $out_trade_no = explode('_', $out_trade_no);
        $out_trade_no = $out_trade_no[0];
        //==商户根据实际情况设置相应的处理流程，此处仅作举例=======

        //以log文件形式记录回调信息
        //         $log_ = new Log_();
        $log_name = __ROOT__ . "/notify_url.log";//log文件路径

        log_result($log_name, "【接收到的notify通知】:\n" . $xml . "\n");

        if ($notify->checkSign() == TRUE) {
            if ($notify->data["return_code"] == "FAIL") {
                //此处应该更新一下订单状态，商户自行增删操作
                log_result($log_name, "【通信出错】:\n" . $xml . "\n");
                echo 'error';
            } elseif ($notify->data["result_code"] == "FAIL") {
                //此处应该更新一下订单状态，商户自行增删操作
                log_result($log_name, "【业务出错】:\n" . $xml . "\n");
                echo 'error';
            } else {
                //此处应该更新一下订单状态，商户自行增删操作
                $res = $notify->data["result_code"];
                switch ($res) {
                    case 'SUCCESS';
                        $status = get_order_status($out_trade_no, '10');
                        if ($status) {
                            update_order_status($out_trade_no, $out_trade_no, '20', '微信');
                        }
                        log_result($log_name, "【支付成功】:\n" . $xml . "\n");
                        echo 'SUCCESS';
                        break;
                    case 'NOTPAY';
                        echo 'NOTPAY';
                        break;
                    default:
                        echo 'ERROR';
                        break;
                }
            }
        }
    }
    public function order_info(){
        $order_no = I('post.order_no');
        $uid = $this->uid;
        if($order_no){
            $order=M('order');
            $order_goods=M('order_goods');
            $order_info_s=$order->where("buyer_id=$uid and order_cn='$order_no'")->select();
            $order_info_d=$order->where('buyer_id='.$uid.' and order_sn='.$order_no)->find();
            if($order_info_s){
                $order_info=$order->where('buyer_id='.$uid.' and order_id='.$order_info_s[0]['order_id'])->find();
                $order_goods_info=array();
                $youhui_price=0;
                foreach($order_info_s as $key=>$value){
                    $order_good=$order_goods->where('order_id='.$value['order_id'])->select();
                    $order_goods_info=array_merge($order_goods_info,$order_good);
                    $youhui_price_s=get_coupon_price($value['buyer_id'],$value['coupon']);
                    $youhui_price=$youhui_price+$youhui_price_s;
                }
            }elseif($order_info_d){
                $order_info=$order_info_d;
                $order_goods_info=$order_goods->where('order_id='.$order_info_d['order_id'])->select();
                $youhui_price=get_coupon_price($order_info_d['buyer_id'],$order_info_d['coupon']);
            }
            if($order_info['tuanselect']==1&&$order_info['refund_state']==0&&$order_info['order_state']=='20'){
                if($order_info['tuan_is_first_id']==0){
                    $tuan_pay_time=$order_info['payment_time'];
                    $num=$order_info['tuannum']-get_tuan($order_info['order_id']);
                }else{
                    $first_tuan=$order->find($order_info['tuan_is_first_id']);
                    $tuan_pay_time=$first_tuan['payment_time'];
                    $num=$first_tuan['tuannum']-get_tuan($order_info['tuan_is_first_id']);
                }
            }
            $data['order_goods_info']=$order_goods_info;
            $data['order_info']=$order_info;
            $data['num']=$num;
            $data['tuan_pay_time']=$tuan_pay_time;
            $data['order_no']=$order_no;
            $data['youhui_price']=$youhui_price;
            $this->ajax_r(1, '成功', $data);
        }else{
            $this->ajax_r(0, '订单号为空');
        }
    }

   public function ctuan(){
        $id=I('post.order_id');
        //$uid = $this->uid;
        $order_info=M('order')->find($id);
        $order_good=M('order_goods')->where('order_id='.$id)->find();
        if($order_info['tuan_is_first_id']==0){
            $tuan_is_first_id=$id;
        }else{
            $tuan_is_first_id=$order_info['tuan_is_first_id'];
        }
        $first=M('order')->find($tuan_is_first_id);
        if($first['refund_state']>0){
           $this->ajax_r(0, '该团已过期');
        }
        $tuan_pay_time=$first['payment_time'];
        $num=$first['tuannum']-get_tuan($tuan_is_first_id);
        $buy_ids=M('order')->field('yt_order.buyer_id,yt_order.tuan_is_first_id')->where('(tuan_is_first_id='.$tuan_is_first_id.' or order_id='.$tuan_is_first_id.') and order_state>"10"')->select();
        //print_r(M('order')->getLastSql());
        $buy_users=array();
        if(is_array($buy_ids)){
            foreach ($buy_ids as $key=>$val){
                $users=M('users')->find($val['buyer_id']);
                if($users['wx_name']){
                    $buy_users[$key]['username']=$users['wx_name'];
                }else {
                    $buy_users[$key]['username'] = $users['username'];
                }
                $users['user_pic']=$users['user_pic']?$users['user_pic']:'/themes/wnsc/Home/User/images/default_user_pic.png';
                if(strpos($users['user_pic'],"https")===0){
                    $buy_users[$key]['header_pic']=$users['user_pic'];
                }else{
                    $buy_users[$key]['header_pic']="https://m.58daiyan.com".$users['user_pic'];
                }
                if($val['tuan_is_first_id']==0){
                    $buy_users[$key]['is_first']=1;
                }else{
                    $buy_users[$key]['is_first']=0;
                }
            }
        }
        $shop_info=M('shop')->where('id='.$order_good['goods_id'])->find();
        $shop_info['shop_sku']=json_decode($shop_info['shop_sku'],true);
        $data['tuan_is_first_id']=$tuan_is_first_id;
        $data['num']=$num;
        $data['tuan_pay_time']=$tuan_pay_time;
        $data['order_info']=$order_info;
        $data['order_good']=$order_good;
        $data['shop_info']=$shop_info;
        $data['buy_users']=$buy_users;
        $this->ajax_r(1, '成功',$data);
    }

    public function callback()
    {
        $getData = I('post.');
        $out_trade_no = $getData['order_no'];
        $trade_no = $getData['trade_no'] ? $getData['trade_no'] : $getData['order_no'];
        $status = $getData['status'] ? $getData['status'] : 20;
        $payway = $getData['payway'] ? $getData['payway'] : '微信';
        if (empty($trade_no) && empty($status) && empty($out_trade_no)) {
            $datas['status'] = 0;
            $datas['message'] = '参数为空';
            $datas = json_encode($datas);
            die($datas);
        }
        $order = M('order');
        $flag = true;
        $result = $order->where('order_cn=' . $out_trade_no)->select();
        if ($result) {
            $order_add_time = $result[0]['add_time'];
            foreach ($result as $key => $value) {
                $data['order_id'] = $value['order_id'];
                $data['pay_sn'] = $trade_no;
                //免发货
                if ($value['mian_send'] == 1 && $status == 20) {
                    //判断拼团是否成功
                    if ($value['tuanselect'] == 1) {
                        if ($value['tuan_is_first_id'] == 0) {
                            $num = get_tuan($value['order_id']);
                            $tuan_m_send['order_id'] = $value['order_id'];
                        } else {
                            $num = get_tuan($value['tuan_is_first_id']);
                            $tuan_m_send['order_id'] = $value['tuan_is_first_id'];
                        }
                        if ($num == $value['tuannum']) {
                            $data['order_state'] = '30';
                            $data['shipping_time'] = time();
                            $tuan_m_send['status'] = 1;
                        } else {
                            $data['order_state'] = $status;
                            $tuan_m_send['status'] = 0;
                        }
                    } else {
                        $data['order_state'] = '30';
                        $data['shipping_time'] = time();
                    }
                } else {
                    $data['order_state'] = $status;
                }
                $data['payment_code'] = $payway;
                $data['payment_time'] = time();
                $rs = $order->save($data);
                $uid = $value['buyer_id'];
                //减库存
                if ($status == 20) {
                    $good_list = M('order_goods')->field('goods_id,goods_num,goods_pay_price,goods_sku,goods_sku_spec,goods_sku_style')->where('order_id=' . $value['order_id'])->select();
                    foreach ($good_list as $k => $v) {
                        if ($v['goods_sku'] == 0) {
                            M('shop')->where('id=' . $v['goods_id'])->setDec('num', $v['goods_num']);
                        } else {
                            M('shop_sku')->where('sku_id=' . $v['goods_sku'])->setDec('sku_stock', $v['goods_num']);
                            $sku_shop_info = M('shop')->find($v['goods_id']);
                            $sku = json_decode($sku_shop_info['shop_sku'], true);
                            $from = $sku['SKU_Form'];
                            foreach ($from as $k2 => $v2) {
                                if ($v['goods_sku_spec'] == $v2['sku_spec'] && $v['goods_sku_style'] == $v2['sku_style']) {
                                    $sku['SKU_Form'][$k2]['sku_stock'] = $v2['sku_stock'] - $v['goods_num'];
                                }
                            }
                            $update_sku['shop_sku'] = json_encode($sku);
                            $update_sku['id'] = $v['goods_id'];
                            M('shop')->save($update_sku);
                        }
                        //增加销量
                        M('shop')->where('id=' . $v['goods_id'])->setInc('sale_num', $v['goods_num']);
                        //增加众筹销量和金额
                        M('crowdfunding')->where('goods_id=' . $v['goods_id'])->setInc('num', $v['goods_num']);
                        M('crowdfunding')->where('goods_id=' . $v['goods_id'])->setInc('now_money', $v['goods_pay_price']);


                    }
                }
                //判断拼团是否成功
                if ($value['tuanselect'] == 1) {
                    if ($value['tuan_is_first_id'] == 0) {
                        $num = get_tuan($value['order_id']);
                    } else {
                        $num = get_tuan($value['tuan_is_first_id']);
                    }
                    if ($num == $value['tuannum']) {
                        $newdata['tuan_is_success'] = 1;
                        //拼团成功时的订单肯定是子订单
                        $order->where('tuan_is_first_id=' . $value['tuan_is_first_id'])->save($newdata);
                        $order->where('order_id=' . $value['tuan_is_first_id'])->save($newdata);
                    }
                }
                if (!$rs) {
                    $flag = false;
                }
            }
        } else {
            $result = $order->where('order_sn=' . $out_trade_no)->find();
            $order_add_time = $result['add_time'];
            $data['order_id'] = $result['order_id'];
            $data['pay_sn'] = $trade_no;
            //免发货
            if ($result['mian_send'] == 1 && $status == 20) {
                //判断拼团是否成功
                if ($result['tuanselect'] == 1) {
                    if ($result['tuan_is_first_id'] == 0) {
                        $num = get_tuan($result['order_id']);
                        $tuan_m_send['order_id'] = $result['order_id'];
                    } else {
                        $num = get_tuan($result['tuan_is_first_id']);
                        $tuan_m_send['order_id'] = $result['tuan_is_first_id'];
                    }
                    if ($num == $result['tuannum']) {
                        $data['order_state'] = '30';
                        $data['shipping_time'] = time();

                        $tuan_m_send['status'] = 1;
                    } else {
                        $data['order_state'] = $status;
                        $tuan_m_send['status'] = 0;
                    }
                } else {
                    $data['order_state'] = '30';
                    $data['shipping_time'] = time();
                }
            } else {
                $data['order_state'] = $status;
            }
            $data['payment_code'] = $payway;
            $data['payment_time'] = time();
            $rs = $order->save($data);
            $uid = $result['buyer_id'];
            //减库存
            if ($status == 20) {
                $good_list = M('order_goods')->field('goods_id,goods_num,goods_pay_price,goods_sku,goods_sku_spec,goods_sku_style')->where('order_id=' . $result['order_id'])->select();
                foreach ($good_list as $k => $v) {
                    if ($v['goods_sku'] == 0) {
                        M('shop')->where('id=' . $v['goods_id'])->setDec('num', $v['goods_num']);
                    } else {
                        M('shop_sku')->where('sku_id=' . $v['goods_sku'])->setDec('sku_stock', $v['goods_num']);
                        $sku_shop_info = M('shop')->find($result['goods_id']);
                        $sku = json_decode($sku_shop_info['shop_sku'], true);
                        $from = $sku['SKU_Form'];
                        foreach ($from as $k2 => $v2) {
                            if ($v['goods_sku_spec'] == $v2['sku_spec'] && $v['goods_sku_style'] == $v2['sku_style']) {
                                $sku['SKU_Form'][$k2]['sku_stock'] = $v2['sku_stock'] - $v['goods_num'];
                            }
                        }
                        $update_sku['shop_sku'] = json_encode($sku);
                        $update_sku['id'] = $v['goods_id'];
                        M('shop')->save($update_sku);
                    }
                    //增加销量
                    M('shop')->where('id=' . $v['goods_id'])->setInc('sale_num', $v['goods_num']);
                    //增加众筹销量和金额
                    M('crowdfunding')->where('goods_id=' . $v['goods_id'])->setInc('num', $v['goods_num']);
                    M('crowdfunding')->where('goods_id=' . $v['goods_id'])->setInc('now_money', $v['goods_pay_price']);

                }
            }
            //判断拼团是否成功
            if ($result['tuanselect'] == 1) {
                if ($result['tuan_is_first_id'] == 0) {
                    $num = get_tuan($result['order_id']);
                } else {
                    $num = get_tuan($result['tuan_is_first_id']);
                }
                if ($num == $result['tuannum']) {
                    $newdata['tuan_is_success'] = 1;
                    //拼团成功时的订单肯定是子订单
                    $order->where('tuan_is_first_id=' . $result['tuan_is_first_id'])->save($newdata);
                    $order->where('order_id=' . $result['tuan_is_first_id'])->save($newdata);
                }
            }
            if (!$rs) {
                $flag = false;
            }
        }

        //团购免发货
        if ($flag && $tuan_m_send['status'] == 1) {
            $m_data['order_state'] = '30';
            $m_data['shipping_time'] = time();
            $order->where('tuan_is_first_id=' . $tuan_m_send['order_id'])->save($m_data);
            $order->where('order_id=' . $tuan_m_send['order_id'])->save($m_data);
        }
        //支付成功通知
        if ($flag && $status == 20) {

            $user_info = M('users')->find($uid);

            if ($user_info['wx_h5openid']) {
                $openid = $user_info['wx_h5openid'];
                $url = 'https://m.58daiyan.com/user/order_info/order/' . $out_trade_no;
                $keyword1 = $out_trade_no;
                $keyword2 = date('Y年m月d日  H:i', time());
                $keyword3 = get_count_price($out_trade_no);
                $keyword4 = $payway;
                send_info($openid, $url, $keyword1, $keyword2, $keyword3, $keyword4);
            }

        }

        //收货代言通知
        if ($flag && $status == 40) {

            $user_info = M('users')->find($uid);

            if ($user_info['wx_h5openid']) {
                $openid = $user_info['wx_h5openid'];
                $url = 'https://m.58daiyan.com/user/daiyan.html';
                $keyword1 = date('Y年m月d日  H:i', $order_add_time);;
                $keyword2 = $out_trade_no;
                send_info_daiyan($openid, $url, $keyword1, $keyword2);
            }

        }
        if ($flag) {
            $this->ajax_r(1, '成功！');
        } else {
            $this->ajax_r(0, '失败！');
        }
        //return $flag;
    }


    /**
     * 待付款订单需要的数据
     */
    public function orderInfo($uid, $store_id, $cart_ids)
    {
        $users_address = M('users_address');
        $useraddress = $users_address->where('user_id=' . $uid . ' and is_default=1')->find();
        $city_id = $useraddress['city'];

        $cart_list_id = explode(',', $cart_ids);

        $cartModel = M('cart');
        $shop_sku = M('shop_sku');
        $shop = M('shop');
        $store = M('store');
        $result = array();
        $total_num = $total_price = $daiyan_sale = $total_freight = 0;
        $new_coupon_shop_ids = array();
        if (is_array($cart_list_id)) {
            foreach ($cart_list_id as $key => $v) {
                $cart = $cartModel->where('cart_id=' . $v . ' and store_id=' . $store_id . ' and buyer_id=' . $uid)->find();
                if (!empty($cart)) {
                    $rs_shop = $shop->find($cart['shop_id']);
                    $rs_store = $store->find($cart['store_id']);
                    $cart['freight'] = get_freight($cart['shop_id'], $city_id, $cart['num']);
                    $cart['shop_picture'] = $rs_shop['image'];
                    $cart['shop_name'] = $rs_shop['title'];
                    if ($cart['sku_id'] != 0) {
                        $rs_shop_sku = $shop_sku->where('sku_id=' . $cart['sku_id'])->find();

                        $cart['sku_spec'] = $rs_shop_sku['sku_spec'];
                        $cart['sku_style'] = $rs_shop_sku['sku_style'];
                        if ($cart['tuanselect'] == 1) {
                            if ($rs_shop_sku['sku_price_tuan']) {
                                $price = $rs_shop_sku['sku_price_tuan'];
                            } else {
                                $price = $rs_shop['tuan_price'];
                            }
                        } else {
                            $price = $rs_shop_sku['sku_price'];
                        }
                    } else {
                        if ($cart['tuanselect'] == '1') {
                            $price = $rs_shop['tuan_price'];
                        } else {
                            $price = $rs_shop['price'];
                        }
                    }
                    //抵扣券
                    $shop_id = $cart['shop_id'];
                    $invoice = get_web_invoice();
                    $daiyan_start_time = time() - 60 * 60 * 24 * $invoice['web_diyong'];
                    $daiyan_info = M('daiyan')->where("uid=$uid and shop_id=$shop_id and time>$daiyan_start_time")->find();
                    if ($daiyan_info) {
                        $cart['daiyan_sale'] = $rs_shop['dikouquan'];
                    } else {
                        $cart['daiyan_sale'] = 0;
                    }
                    //$cart['id']=$cart['shop_id'].','.$cart['sku_id'];
                    $cart['oprice'] = $rs_shop['oprice'];
                    $cart['price'] = $price;
                    if ($cart['recommend_id']) {
                        $cart['redenvelope'] = $rs_shop['redenvelope'];
                    }
                    $daiyan_sale = $daiyan_sale + ($cart['daiyan_sale'] * $cart['num']);
                    $total_num = $total_num + $cart['num'];
                    $total_freight = $total_freight + $cart['freight'];
                    $total_price = $total_price + ($cart['num'] * $price) - ($cart['num'] * $cart['daiyan_sale']);
                    $cart_list[$key] = $cart;
                    $new_coupon_shop_ids[$key] = $cart['shop_id'];
                }
            }
            $result['total_freight'] = $total_freight;
            $result['daiyan_sale'] = $daiyan_sale;
            $result['total_num'] = $total_num;
            $result['total_price'] = $total_price;
            $result['new_coupon_shop_ids'] = implode(',', $new_coupon_shop_ids);
        }
        $result['cart_list'] = $cart_list;
        return $result;
    }

    public function address($uid)
    {
        $users = M('users');
        $users_address = M('users_address');
        if ($uid) {
            $userinfo = $users->find($uid);
            $useraddress = $users_address->where('user_id=' . $uid . ' and is_default=1')->limit(1)->select();
            foreach ($useraddress as $key => $value) {
                $province = getProvinceInfo($value['province']);
                $city = getCityInfo($value['city']);
                $district = getDistrictInfo($value['district']);
                $useraddress[$key]['province'] = $province['province_name'];
                $useraddress[$key]['city'] = $city['city_name'];
                $useraddress[$key]['district'] = $district['district_name'];
            }
            return $useraddress;
        }
    }

    //生成订单号
    public function build_order_no()
    {
        $no = date('Ymd') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
        //检测是否存在
        $db = M('order');
        $info = $db->where(array('order_sn' => $no))->find();
        (!empty($info)) && $no = $this->build_order_no();
        return $no;

    }

    //查询订单
    public function orderQuery2($trade_no, $store_id)
    {
        $out_trade_no = $trade_no;
        //使用订单查询接口
        $orderQuery = new \OrderQuery_pub();
        //设置必填参数
        //appid已填,商户无需重复填写
        //mch_id已填,商户无需重复填写
        //noncestr已填,商户无需重复填写
        //sign已填,商户无需重复填写
        $orderQuery->setParameter("out_trade_no", "$out_trade_no");//商户订单号
        //非必填参数，商户可根据实际情况选填
        //$orderQuery->setParameter("sub_mch_id","XXXX");//子商户号
        //$orderQuery->setParameter("transaction_id","XXXX");//微信订单号
        $options   =   D('options');
        $option_name='wx_store_'.$store_id;
        //获取小程序配置
        $w_data['option_name']=$option_name;
        $new_w_data=$options->where($w_data)->find();
        $w_config=json_decode($new_w_data['option_value']);
        $smallRoutineInfo=get_object_vars($w_config);
        $appid = $smallRoutineInfo['APP_KEY'];
        $mch_id =$smallRoutineInfo['MCHID'];
        $key = $smallRoutineInfo['MCHID_KEY'];

        $orderQuery->setAPPID($appid);
        $orderQuery->setMCHID($mch_id);
        $orderQuery->setMCHKEY($key);
        //获取订单查询结果
        $orderQueryResult = $orderQuery->getResult();

        //商户根据实际情况设置相应的处理流程,此处仅作举例
        if ($orderQueryResult["return_code"] == "FAIL") {
            return false;
            die;
        } elseif ($orderQueryResult["result_code"] == "FAIL") {
            return false;
            die;
        } else {
            $res = $orderQueryResult["trade_state"];
            switch ($res) {
                case 'SUCCESS';
                    $status = get_order_status($out_trade_no, '10');
                    if ($status) {
                        update_order_status($out_trade_no, $orderQueryResult["transaction_id"], '20', '微信');
                        //dump($orderQueryResult);
                    }
                    return true;
                    break;
                case 'NOTPAY';
                    return false;
                    break;
                default:
                    return false;
                    break;
            }


        }

    }

    //生成linux系统随机数
    public function rd_session($len)
    {
        $fp = @fopen('/dev/urandom', 'rb');
        $result = '';
        if ($fp !== FALSE) {
            $result .= @fread($fp, $len);
            @fclose($fp);
        } else {
            trigger_error('Can not open /dev/urandom.');
        }
        $result = base64_encode($result);
        $result = strtr($result, '+/', '-_');
        return substr($result, 0, $len);
    }

    //获取openId
    public function getOpenId($code, $store_id)
    {
        $options   =   D('options');
        $option_name='wx_store_'.$store_id;
        //获取小程序配置
        $w_data['option_name']=$option_name;
        $new_w_data=$options->where($w_data)->find();
        $w_config=json_decode($new_w_data['option_value']);
        $smallRoutineInfo=get_object_vars($w_config);
        $appid = $smallRoutineInfo['APP_KEY'];
        $appsecret =$smallRoutineInfo['APP_SECRET'];
        $url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' . $appid . '&secret=' . $appsecret . '&js_code=' . $code . '&grant_type=authorization_code';
        file_put_contents("pay.txt", date("Y-m-d H:i:s") . "url   " . print_r($url, true) . "\r\n", FILE_APPEND);
        $rs1 = file_get_contents($url);
        $rs = json_decode($rs1, TRUE);
        file_put_contents("pay.txt", date("Y-m-d H:i:s") . "rs   " . print_r($rs, true) . "\r\n", FILE_APPEND);
        //\Think\Log::write("session :\n" . print_r($rs, true) . "\n",'storeApi/session' . date('Y-m-d'));
        if (empty($rs['errcode'])) {
            $redis = connectRedis();
            $redis->set('session_key', $rs['session_key']);
            $redis->set('openid', $rs['openid']);
            return $rs;
        } else {
            return $rs;
        }
    }

    public function ajax_r($status = '0', $message = '', $data = '')
    {
        $datas['status'] = $status;
        $datas['message'] = $message;
        $datas['data'] = $data;
        $datas = json_encode($datas);
        die($datas);
    }
}

?>
